使用帖子正文上传http文件

时间:2018-01-03 09:13:53

标签: android multipart okhttp3

我正在尝试上传文件以及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());

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

提前致谢

2 个答案:

答案 0 :(得分:0)

尝试以下代码:

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();
                }
            }
        });
    }

答案 1 :(得分:0)

 @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作为文件选择器