Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/222.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android将图像发送到Web服务器_Android_Image_Webserver - Fatal编程技术网

Android将图像发送到Web服务器

Android将图像发送到Web服务器,android,image,webserver,Android,Image,Webserver,我的任务是将我用应用程序拍摄的照片发送到Web服务器。这是我的相机活动,我想用onActivityResult方法发送图像。我很难找到最新的解决方案,因为我所能找到的似乎都是使用现在已被弃用的MultipartEntity package com.ndjk; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; imp

我的任务是将我用应用程序拍摄的照片发送到Web服务器。这是我的相机活动,我想用onActivityResult方法发送图像。我很难找到最新的解决方案,因为我所能找到的似乎都是使用现在已被弃用的MultipartEntity

package com.ndjk;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ImageView;

public class CameraActivity extends Activity {

private static final int CAMERA_REQUEST = 1888;
public ImageView imageView;
public static final String URI_PATH = "Uri";
Uri imageUri = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_frontpage);
    imageView = (ImageView) findViewById(R.id.pictureImageView);
    open();

}

public void open() {
    Intent cameraIntent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    Bitmap bp = (Bitmap) data.getExtras().get("data");
    imageView.setImageBitmap(bp);

    Intent frontPageIntent = new Intent(this, FrontPageActivity.class);
    imageUri = data.getData();

    frontPageIntent.putExtra(URI_PATH, imageUri.toString());
    frontPageIntent.putExtra("MapPhoto", bp);

    startActivity(frontPageIntent);
    }

    }

我认为答案如下:


您应该使用MultipartEntityBuilder作为备选方案

编辑-1

您可以使用以下代码打开相机:

    private static final int RESULT_TAKE_PHOTO = 1;
    Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(i, RESULT_TAKE_PHOTO);
您的
onActivityResult
必须如下所示:

if (resultCode == RESULT_OK) {
            File file = null;
            String filePath = null;
            try {

                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                filePath = cursor.getString(columnIndex);
                cursor.close();

                rotateDegree = getCameraPhotoOrientation(getApplicationContext(), selectedImage, picturePath);
                bmp = BitmapFactory.decodeFile(picturePath);
                bmp = rotateImage(bmp, rotateDegree);

                file = new File(filePath);
                FileOutputStream fOut = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
                fOut.flush();
                fOut.close();
                resultCode=0;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
因此,如果拍摄照片,您可以使用此任务进行发送。您可以在向服务器发送文件时显示进度条。这对我有用

public class SendFile extends AsyncTask<String, Integer, Integer> {

    private Context conT;
    private ProgressDialog dialog;
    private String SendUrl = "";
    private String SendFile = "";
    private String Parameters = "";
    private String result;
    public File file;

    SendFile(Context activity, String url, String filePath, String values) {
        conT = activity;
        dialog = new ProgressDialog(conT);
        SendUrl = url;
        SendFile = filePath;
        Parameters = Values;
    }

    @Override
    protected void onPreExecute() {
        file = new File(SendFile);
        dialog.setMessage("Please Wait..");
        dialog.setCancelable(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setMax((int) file.length());
        dialog.show();
    }

    @Override
    protected Integer doInBackground(String... params) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        InputStream inputStream = null;
        String twoHyphens = "--";
        String boundary = "*****"
                + Long.toString(System.currentTimeMillis()) + "*****";
        String lineEnd = "\r\n";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 512;

        String[] q = SendFile.split("/");
        int idx = q.length - 1;
        try {

            FileInputStream fileInputStream = new FileInputStream(file);

            URL url = new URL(SendUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);

            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("User-Agent",
                    "Android Multipart HTTP Client 1.0");
            connection.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + boundary);

            outputStream = new DataOutputStream(
                    connection.getOutputStream());
            outputStream.writeBytes(twoHyphens + boundary + lineEnd);
            outputStream
                    .writeBytes("Content-Disposition: form-data; name=dosya; filename=\""
                            + q[idx] + "\"" + lineEnd);
            outputStream.writeBytes("Content-Type: image/jpg" + lineEnd);
            outputStream.writeBytes("Content-Transfer-Encoding: binary"
                    + lineEnd);
            outputStream.writeBytes(lineEnd);

            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];

            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
            int boyut = 0;
            while (bytesRead > 0) {
                boyut += bytesRead;
                outputStream.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                dialog.setProgress(boyut);
            }

            outputStream.writeBytes(lineEnd);

            String[] posts = Bilgiler.split("&");
            int max = posts.length;
            for (int i = 0; i < max; i++) {
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);
                String[] kv = posts[i].split("=");
                outputStream
                        .writeBytes("Content-Disposition: form-data; name=\""
                                + kv[0] + "\"" + lineEnd);
                outputStream.writeBytes("Content-Type: text/plain"
                        + lineEnd);
                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(kv[1]);
                outputStream.writeBytes(lineEnd);
            }

            outputStream.writeBytes(twoHyphens + boundary + twoHyphens
                    + lineEnd);
            inputStream = connection.getInputStream();
            result = this.convertStreamToString(inputStream);
            Log.v("TAG","result:"+result);
            fileInputStream.close();
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {

        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        dialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(Integer result1) {
        dialog.dismiss();
    };

    private String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

作为替代方案,我强烈建议使用从Square改装REST库

您可以创建如下Java接口:

@Multipart
@POST("/webservice/{userid}/avatar.json")
Object uploadImage(
        @Header("Rest-User-Token") String token,
        @Path("userid") String userId,
        @Part("FileData") TypedFile pictureFile

);
然后,将意图数据转换为文件对象,然后按如下方式创建TypedFile:

TypedFile in = new TypedFile("image/jpeg", imageFile);
@Multipart
@POST("/webservice/{userid}/avatar.json")
Object uploadImage(
        @Header("Rest-User-Token") String token,
        @Path("userid") String userId,
        @Part("FileData") TypedFile pictureFile

);
TypedFile in = new TypedFile("image/jpeg", imageFile);