猿问

使用 volley 在 post 请求正文中使用多部分数据将图像上传到服务器

我正在尝试使用截击将图像上传到服务器,我遵循了一些教程,但就我而言,我需要在发布请求的正文中传递多部分数据。


   private void uploadBitmap(final Bitmap bitmap) throws JSONException {


    //our custom volley request

    String URL = "https://<---------->/me/avatar";


    JSONObject jsonBody = new JSONObject();


    jsonBody.put("avatar", new VolleyMultipartRequest.DataPart( "index.png", getFileDataFromDrawable(bitmap)));

    final String requestBody = jsonBody.toString();

    VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL,

            new Response.Listener<NetworkResponse>() {

                @Override

                public void onResponse(NetworkResponse response) {

                    loading.setVisibility(View.GONE);

                    Toast.makeText(ProfileSettings.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();

                    try {

                        JSONObject obj = new JSONObject(new String(response.data));


                    } catch (JSONException e) {

                        e.printStackTrace();

                    }

                }

            },

            new Response.ErrorListener() {

                @Override

                public void onErrorResponse(VolleyError error) {

                    loading.setVisibility(View.GONE);

                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();

                }

            }) {



        @Override

        public Map<String, String> getHeaders() throws AuthFailureError {

            Map<String, String> params = new HashMap<String, String>();

            params.put("Content-Type", "application/json; charset=UTF-8");

            params.put("Authorization", "Bearer " + jsonToken);

            return params;

        }

我从教程中获得了这段代码,但他们给出了 500 错误,所以我猜这可能是因为我需要在请求正文中传递“avatar”:“index.png”而不是这种方式。


白猪掌柜的
浏览 83回答 2
2回答

慕尼黑的夜晚无繁华

点击这些链接 -&nbsp;https://www.simplifiedcoding.net/upload-image-to-server/&nbsp;https://www.simplifiedcoding.net/android-upload-image-to-server/并使用此库上传图像和文件 -&nbsp;https://github.com/gotev/android-upload-service。请按照上面的教程介绍这些库。

慕婉清6462132

我能够使用改造 2 实现此目的,这是代码。@Overrideprotected void onActivityResult(int requestCode, int resultCode, Intent data) {&nbsp; &nbsp; super.onActivityResult(requestCode, resultCode, data);&nbsp; &nbsp; if (requestCode == 100 && resultCode == RESULT_OK && data != null) {&nbsp; &nbsp; &nbsp; &nbsp; //getting the image Uri&nbsp; &nbsp; &nbsp; &nbsp; Uri imageUri = data.getData();&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //getting bitmap object from uri&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //displaying selected image to imageview&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logo.setImageBitmap(bitmap);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //calling the method uploadBitmap to upload image&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; loading.setVisibility(View.VISIBLE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ///uploadBitmap(bitmap);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; File file = new File(getRealPathFromUri(this, imageUri));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; uploadImageFile(file);&nbsp; &nbsp; &nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public static String getRealPathFromUri(Context context, Uri contentUri) {&nbsp; &nbsp; Cursor cursor = null;&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; String[] proj = { MediaStore.Images.Media.DATA };&nbsp; &nbsp; &nbsp; &nbsp; cursor = context.getContentResolver().query(contentUri, proj, null, null, null);&nbsp; &nbsp; &nbsp; &nbsp; int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);&nbsp; &nbsp; &nbsp; &nbsp; cursor.moveToFirst();&nbsp; &nbsp; &nbsp; &nbsp; return cursor.getString(column_index);&nbsp; &nbsp; } finally {&nbsp; &nbsp; &nbsp; &nbsp; if (cursor != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cursor.close();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}private void uploadImageFile(File file) throws IOException {&nbsp; &nbsp; file&nbsp; = new Compressor(this).compressToFile(file);&nbsp; &nbsp; RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);&nbsp; &nbsp; // MultipartBody.Part is used to send also the actual filename&nbsp; &nbsp; MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);&nbsp; &nbsp; ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);&nbsp; &nbsp; Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);&nbsp; &nbsp; call.enqueue(new Callback< ServerResponse >() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onResponse(@NonNull Call < ServerResponse > call, @NonNull retrofit2.Response<ServerResponse> response) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ServerResponse serverResponse = response.body();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (serverResponse.getData() != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.e(TAG, "Response is "+ serverResponse.getData());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;loading.setVisibility(View.GONE);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.e("Response", String.valueOf(serverResponse));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void onFailure(Call < ServerResponse > call, Throwable t) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Log.e(TAG, t.getMessage());&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp;// Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());&nbsp; &nbsp; }
随时随地看视频慕课网APP

相关分类

Java
我要回答