使用帖子正文上传http文件

问题描述 投票:1回答:2

我正在尝试上传文件以及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 multipart okhttp3
2个回答
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();
                }
            }
        });
    }

0
投票
 @Multipart
    @POST("/api/index.php?tag=sendFile")
    Call<Object> sendCurrentFileAPI(
                                    @Part("file") RequestBody  designation, @Part MultipartBody.Part file);

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

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

© www.soinside.com 2019 - 2024. All rights reserved.