亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 volley 在 post 請求正文中使用多部分數據將圖像上傳到服務器

使用 volley 在 post 請求正文中使用多部分數據將圖像上傳到服務器

白豬掌柜的 2023-02-16 16:25:50
我正在嘗試使用截擊將圖像上傳到服務器,我遵循了一些教程,但就我而言,我需要在發布請求的正文中傳遞多部分數據。   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”而不是這種方式。
查看完整描述

2 回答

?
慕尼黑的夜晚無繁華

TA貢獻1864條經驗 獲得超6個贊

點擊這些鏈接 - https://www.simplifiedcoding.net/upload-image-to-server/ https://www.simplifiedcoding.net/android-upload-image-to-server/

并使用此庫上傳圖像和文件 - https://github.com/gotev/android-upload-service。

請按照上面的教程介紹這些庫。


查看完整回答
反對 回復 2023-02-16
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

我能夠使用改造 2 實現此目的,這是代碼。


@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == 100 && resultCode == RESULT_OK && data != null) {


        //getting the image Uri

        Uri imageUri = data.getData();

        try {

            //getting bitmap object from uri

            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);


            //displaying selected image to imageview

            logo.setImageBitmap(bitmap);


            //calling the method uploadBitmap to upload image

            loading.setVisibility(View.VISIBLE);

            ///uploadBitmap(bitmap);


            File file = new File(getRealPathFromUri(this, imageUri));

            uploadImageFile(file);


        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


public static String getRealPathFromUri(Context context, Uri contentUri) {

    Cursor cursor = null;

    try {

        String[] proj = { MediaStore.Images.Media.DATA };

        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        cursor.moveToFirst();

        return cursor.getString(column_index);

    } finally {

        if (cursor != null) {

            cursor.close();

        }

    }

}


private void uploadImageFile(File file) throws IOException {


    file  = new Compressor(this).compressToFile(file);

    RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);

    // MultipartBody.Part is used to send also the actual filename

    MultipartBody.Part body = MultipartBody.Part.createFormData("avatar", file.getName(), requestFile);


    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);

    Call<ServerResponse> call = getResponse.uploadFile("Bearer "+jsonToken, body);

    call.enqueue(new Callback< ServerResponse >() {

        @Override

        public void onResponse(@NonNull Call < ServerResponse > call, @NonNull retrofit2.Response<ServerResponse> response) {

            ServerResponse serverResponse = response.body();


            if (serverResponse.getData() != null) {

                Log.e(TAG, "Response is "+ serverResponse.getData());

               loading.setVisibility(View.GONE);

                Toast.makeText(ProfileSettings.this, "Avatar updated", Toast.LENGTH_SHORT).show();

            } else {

                Log.e("Response", String.valueOf(serverResponse));

            }

        }



        @Override

        public void onFailure(Call < ServerResponse > call, Throwable t) {

            Log.e(TAG, t.getMessage());

        }

    });

       // Log.e(TAG, "request is "+call.request().body()+" and "+call.request().headers());

    }


查看完整回答
反對 回復 2023-02-16
  • 2 回答
  • 0 關注
  • 106 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號