【问题标题】:http file upload with post body带有帖子正文的http文件上传
【发布时间】:2018-01-03 09:13:53
【问题描述】:

我正在尝试将文件与JSON 发布正文一起上传。我尝试过这样的事情:

requestBody  = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("data", uploadFileName[1], RequestBody.create(MEDIA_TYPE_JPEG, file))
            .addFormDataPart("name", uploadFileName[1])
            .addFormDataPart("body",postBody)
            .build();

注意:如果我想通过删除上传没有帖子正文的文件,上面的代码可以工作

   .addFormDataPart("body",postBody)

我也尝试创建文件和帖子正文的 ByteOutputArray 并尝试创建ResquestBody

类似这样的:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment;filename=\"" + uploadFileName + "\"\r\n").getBytes("UTF-8"));
baos.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes("UTF-8"));
byte[] buffer = new byte[102400];// 100KB
int read = imageInputStream.read(buffer);
while (read >= 0) {
    baos.write(buffer);
    read = imageInputStream.read(buffer);
}
baos.write(("\r\n").getBytes("UTF-8"));
baos.write((boundaryStr).getBytes("UTF-8"));
baos.write(("Content-Disposition: attachment; name=\"" + fileNameText + "\"\r\n\r\n").getBytes("UTF-8"));
baos.write((postData).getBytes("UTF-8"));
baos.write(("\r\n").getBytes("UTF-8"));
baos.write(("--" + boundary + "--\r\n").getBytes("UTF-8"));
baos.flush();

MediaType MEDIA_TYPE_JPEG  = MediaType.parse(fileType);
RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JPEG,baos.toByteArray());

但没有任何效果。请帮忙。

【问题讨论】:

    标签: android okhttp multipart


    【解决方案1】:

    试试下面的代码:

    private void chooseImageFile(){
            Intent intent = new Intent() ;
            intent.setType("image/*") ;
            intent.setAction(Intent.ACTION_GET_CONTENT) ;
            startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
    
            if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
                Uri imagepath = data.getData() ;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagepath) ;
                    uploadimage.setImageBitmap(bitmap);
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        private String getStringImage(Bitmap bitmap){
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream() ;
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) ;
            byte[] imagebyte = byteArrayOutputStream.toByteArray() ;
            String encodeString = Base64.encodeToString(imagebyte, Base64.DEFAULT) ;
            return encodeString ;
        }
    
    private void callImageUpload() {
            String image_name = imagename.getText().toString().trim() ;
            String bitmap_string = getStringImage(bitmap) ;
            OkHttpClient image_upload_client = new OkHttpClient() ;
            RequestBody postbody = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image", bitmap_string)
                    .addFormDataPart("name", image_name)
                    .build() ;
    
            Request request = new Request.Builder().url(url).post(postbody).build() ;
            setProgressDialouge();
            image_upload_client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
    
                }
    
                @Override
                public void onResponse(Call call, Response response) throws IOException {
    
                    progressDialog.dismiss();
                    String json_string = response.body().string() ;
                    try {
                        JSONObject main_obj = new JSONObject(json_string);
                        final String msg = main_obj.getString("response");
    
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    

    【讨论】:

    【解决方案2】:
     @Multipart
        @POST("/api/index.php?tag=sendFile")
        Call<Object> sendCurrentFileAPI(
                                        @Part("file") RequestBody  designation, @Part MultipartBody.Part file);
    

    我正在使用以下方法在我的活动中上传文件

     MultipartBody.Part multipartBody = null;
        try {
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), uploadingCurrentFile);
    
            multipartBody = MultipartBody.Part.createFormData("file", uploadingCurrentFile.getName(), requestFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), requestBody +"");
    
        mService.sendCurrentFileAPI( selectedDesignationValueRequestBody, multipartBody).enqueue(new Callback<Object>() {
            @Override
            public void onResponse(@NonNull Call<Object> call, @NonNull Response<Object> response) {
    
                if (response.isSuccessful()) {
    
    
            }
    
            @Override
            public void onFailure(@NonNull Call<Object> call, @NonNull Throwable t) {
    
    
    
            }
        });
    

    我也在使用https://github.com/spacecowboy/NoNonsense-FilePicker 文件选择器

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2011-04-24
      • 2012-09-18
      • 2011-01-25
      • 2019-10-16
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 2018-08-05
      相关资源
      最近更新 更多