【问题标题】:How to upload profile pic of a user using MULTIPART/FORM-DATA?如何使用 MULTIPART/FORM-DATA 上传用户的个人资料图片?
【发布时间】:2019-10-17 18:58:51
【问题描述】:

我正在尝试使用 MULTIPART/FORM-DATAg 上传图像(从 mobile 中选择),但由于我是 Multipart 的新手,所以无法弄清楚。 要上传的数据是图片(不是BASE64CODE)和用户ID。

【问题讨论】:

    标签: android android-volley multipartform-data image-uploading


    【解决方案1】:

    这里是使用Multipart上传图片的解决方案

    将此文件添加到依赖项

    //对于多部分

    实现'com.karumi:dexter:5.0.0'

    现在在 Activity 类中,声明这 2 个字段

    private RequestQueue rQueue;
    Uri file_uri_1;
    

    下一步是从link下载文件或复制代码

    现在创建一个函数来上传您的 Imageview

    private void uploadImage() {
    
        ProgressDialog dialog = new ProgressDialog(getActivity());
        dialog.setCancelable(false);
        dialog.setMessage("Please wait...");
        dialog.show();
    
        MultipartRequest volleyMultipartRequest = new MultipartRequest(Request.Method.POST, <URL API URL>,
                new Response.Listener<NetworkResponse>() {
                    @Override
                    public void onResponse(NetworkResponse response) {
    
                        dialog.dismiss();
                        rQueue.getCache().clear();
                        try {
                            JSONObject jsonObject = new JSONObject(new String(response.data));
                                <GET YOUR RESPONSE FROM SEVER HERE>
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        dialog.dismiss();
                        Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }) {
    
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                // Add parameter if you wish send extra parameters with Image
                params.put("<KEY>", <VALUE>);
                return params;
            }
    
    
            @Override
            protected Map<String, DataPart> getByteData() {
                Map<String, DataPart> params = new HashMap<>();
                // Check your file name or path is Empty or not
                if (fileName != null && !fileName.equalsIgnoreCase("")) {
                    File file = new File(filePath);
                    file_uri_1 = Uri.fromFile(file);
                    params.put("<IMAGE KEY>", new DataPart(fileName, getFileDataFromDrawable(getActivity(), file_uri_1), getFileType(file_uri_1)));
                }
    
                return params;
            }
        };
    
    
        volleyMultipartRequest.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        rQueue = Volley.newRequestQueue(getActivity());
        rQueue.add(volleyMultipartRequest);
    }
    
    
    public static byte[] getFileDataFromDrawable(Context context, Uri uri) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            InputStream iStream = context.getContentResolver().openInputStream(uri);
            int bufferSize = 2048;
            byte[] buffer = new byte[bufferSize];
    
            // we need to know how may bytes were read to write them to the byteBuffer
            int len = 0;
            if (iStream != null) {
                while ((len = iStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, len);
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }
    

    希望此代码对您有所帮助。

    【讨论】:

      【解决方案2】:

      当你得到文件路径时试试这个

      onActivityResult

      添加此代码

      String fileName = filePath.substring(filePath.lastIndexOf('/') + 1, filePath.length());
      String ext = fileName.substring(fileName.lastIndexOf("."));
      
      if ((ext.equalsIgnoreCase(".jpg"))
          || (ext.equalsIgnoreCase(".jpeg"))
          || (ext.equalsIgnoreCase(".png"))) {
          // Call method to upload your image 
      } else {
          // Show alert to select Image with above extension
      }
      

      希望这会对你有所帮助。

      【讨论】:

      • 我想使用 Multipart / form-data 上传图片
      猜你喜欢
      • 2015-10-11
      • 2011-03-22
      • 1970-01-01
      • 2020-11-02
      • 2017-05-04
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 2019-08-12
      相关资源
      最近更新 更多