【问题标题】:Android camera image not uploaded to server . Using Multipart data Http postAndroid 相机图像未上传到服务器。使用多部分数据 Http post
【发布时间】:2014-08-27 04:15:02
【问题描述】:

我正在尝试使用 volley 的多部分数据 http post 从相机和画廊上传图像,但是从相机拍摄的图像没有上传,而从画廊上传。

 private void startCamera() {

    Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    // start the image capture Intent
    startActivityForResult(imageIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

 }
 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data)
 {
    switch (requestCode) {

        case CAMERA_CAPTURE_IMAGE_REQUEST_CODE:
            if(resultCode== Activity.RESULT_OK){
                previewCapturedImage();
            }else{
                Toast.makeText(getActivity(),"User cancelled image capture",   Toast.LENGTH_SHORT).show();
            }
            break;
 }

 private void previewCapturedImage() {
    try {
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();
        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;
        Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
                options);
        filePath=fileUri.getPath();
        Matrix matrix = new Matrix();
        matrix.postRotate(90);

        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, options.outWidth, options.outHeight, matrix, true);

        postImageView.setImageBitmap(rotatedBitmap);
        ((TextView)appView.findViewById(R.id.deleteBtn)).setVisibility(View.VISIBLE);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

public  void postFeed(String commentString){
    RequestQueue mqueue = Volley.newRequestQueue(getActivity());
    Map<String, String> params = new HashMap<String, String>();
    params.put("text",commentString);
    params.put("user_id",SettingsHelper.getInstance(getActivity()).getPreference("id"));
    TSUServerRequest.postFeed(getActivity(),mqueue,params,new File(filePath),new Response.Listener<String>() {
        @Override
        public void onResponse(String s) {
            Log.d("a","bscljk");
            filePath="";
            fileUri= null;
            //Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
        }
    },new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            volleyError.printStackTrace();

        }
    });


  public static void postFeed(Context context,RequestQueue queue,Map<String, String> params,File file,
                            Listener<String> listener, ErrorListener errorListener){
    if (TSUServerRequest.checkForConnection(context)) {
        String url =API_CREATE_POST;
        MultiPartRequest myReq = new MultiPartRequest(url,errorListener,listener,file,params);
        queue.add(myReq);
        queue.start();
    }else{
        Toast.makeText(context, "No Internet!Please try again!", Toast.LENGTH_LONG).show();
    }
}

////MultipartRequest.java

public class MultiPartRequest extends Request<String> {

MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "picture";

private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;

public MultiPartRequest(String url, Response.ErrorListener errorListener,
                        Response.Listener<String> listener, File file,
                        Map<String, String> mStringPart) {
    super(Method.POST, url, errorListener);

    mListener = listener;
    mFilePart = file;
    this.mStringPart = mStringPart;
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    buildMultipartEntity();
}

public void addStringBody(String param, String value) {
    mStringPart.put(param, value);
}

private void buildMultipartEntity() {
    entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
    for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
        entity.addTextBody(entry.getKey(), entry.getValue());
    }
}

@Override
public String getBodyContentType() {
    return httpentity.getContentType().getValue();
}

@Override
public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
        httpentity = entity.build();
        httpentity.writeTo(bos);
    } catch (IOException e) {
        VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }
    return bos.toByteArray();
}

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    return Response.success("Uploaded", getCacheEntry());
}

@Override
protected void deliverResponse(String response) {
    mListener.onResponse(response);
}

}

【问题讨论】:

    标签: android image upload android-camera multipart


    【解决方案1】:

    图片未上传的原因是尺寸。 立即从相机拍摄的图像文件太大,因此需要压缩。 从画廊中挑选的相同文件会被上传,因为画廊会在内部压缩文件。

    public File compress(){
    
        File file = new File(filePath);
    
        try {
            Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath());
            if(flagCamera==1) {
                flagCamera=0;
                compressedFile = new File(Environment.getExternalStorageDirectory().toString() + "/compressed" + file.getName());
                FileOutputStream out = new FileOutputStream(compressedFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG,70,out);
                out.flush();
                out.close();
            }else{
                return file;
            }
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return compressedFile;
    
    }
    
    public void postFeed(String commentString) {
        RequestQueue mqueue = Volley.newRequestQueue(getActivity());
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", SettingsHelper.getInstance(getActivity()).getPreference("auth_token"));
        params.put("text", commentString);
        params.put("user_id", SettingsHelper.getInstance(getActivity()).getPreference("id"));
        params.put("privacy", Integer.toString(1));
        TSUServerRequest.postFeed(getActivity(), mqueue, params, compress(), new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d("a", "bscljk");
                filePath = "";
                fileUri = null;
                //Toast.makeText(getActivity(),"Success",Toast.LENGTH_LONG).show();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                volleyError.printStackTrace();
    
            }
        });
    
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-09
    • 2012-06-25
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多