使用 retrofit 上传 pdf 和图像文件

upload pdf and image files using retrofit

我的移动应用程序将 pdf 文件和图像文件上传到服务器。 我可以使用以下代码上传图像文件。

API定义

@Multipart
@POST("/api/images/upload")
Call<ImageUploadResponse> uploadImage(@Header("x-auth-token") String authHeader, @Part List<MultipartBody.Part> image);

在 select 来自存储的任何图像文件

if (requestCode == SELECT_FILE){
 if (data.getClipData() != null) {
   List<byte[]> imageDataList = new ArrayList<>();
   int count = data.getClipData().getItemCount();
   for (int i = 0; i < count; i++) {
     try {
        bmp = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),imageUri);
        bmp.compress(Bitmap.CompressFormat.JPEG, 10, baos);
        imageDataList.add(baos.toByteArray());
      } catch (Exception e) {
       e.printStackTrace();
      }
   }
    uploadImage(imageDataList);
 }

构建多部分 body 部分请求。

private void uploadImage( List<byte[]> imageDataList) {
              
     MultipartBody.Part[]  parts =  new MultipartBody.Part[imageDataList.size()];
     for (int i = 0; i < imageDataList.size(); i++) {
          RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), imageDataList.get(i));
          String fileName = "image" + i + ".jpg";
          MultipartBody.Part body = MultipartBody.Part.createFormData("image", fileName, requestFile);
          parts[i] = body;
  }
 String token = sessionCache.getToken();
 Call<ImageUploadResponse> call = apiInterface.uploadImage(token,parts);
        
 call.enqueue(new Callback<ImageUploadResponse>() {
      @Override
      public void onResponse(Call<ImageUploadResponse> call, Response<ImageUploadResponse> response) {
            List<String> pdfPaths = response.body().getPdf();
            List<String> imagePaths = response.body().getImg();
            Toast.makeText(getContext(), "image scanned/attached",
                                Toast.LENGTH_LONG).show();
           }
        
     @Override
     public void onFailure(Call<ImageUploadResponse> call, Throwablet) {
        
      }
       });
}

如何上传 pdf 文件? 我正在努力从 URI

获取 pdf 文件的绝对路径

openInputStream(uri) 获取 InputStream 并将 InputStream 转换为字节数组解决了图像和 pdf 的问题。从 clipData 获取 mime 类型,并在构造 RequestBody 时使用相同的 mime 类型。

 @Override
 public void onActivityResult(int requestCode, int resultCode, Intent data) {
  ..............
  ..............
  if (requestCode == SELECT_FILE) {
    if (data.getClipData() != null) {
        List<byte[]> imageDataList = new ArrayList<>();
        int count = data.getClipData().getItemCount(); 
        String mimeType = data.getClipData().getDescription().getMimeType(0);
        for (int i = 0; i < count; i++) {
           Uri imageUri = data.getClipData().getItemAt(i).getUri();
           imageDataList.add(getBytes(imageUri));
        }
       // pass the byte array list to be uploaded.
       handleAttachment(imageDataList, mimeType);
     }
}


private byte[] getBytes(Uri uri) {
   try {
      InputStream inputStream = getActivity()
                   .getApplicationContext().getContentResolver().openInputStream(uri);
            return readBytes(inputStream);

        } catch (Exception ex) {
            LOG.d("could not get byte stream",ex)
        }
        return null;
    }

  private byte[] readBytes(InputStream inputStream) throws IOException {
        // this dynamically extends to take the bytes you read
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the byteBuffer
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        // and then we can return your byte array.
        return byteBuffer.toByteArray();
    }

    private void handleAttachment(List<byte[]> imageDataList, String mimeType) {

        List<MultipartBody.Part> parts = new ArrayList<>();
        for (int i = 0; i < imageDataList.size(); i++) {
            MultipartBody.Part body = null;
            switch (mimeType) {
                case MimeTypeConst.imageMimeTypeInRequest:
                    RequestBody requestFile = RequestBody.create(MediaType.parse(MimeTypeConst.imageMimeType),
                            imageDataList.get(i));
                    String fileName = "attachment" + i + ".jpg";
                    body = MultipartBody.Part.createFormData("image", fileName, requestFile);
                    break;
                case MimeTypeConst.pdfMimeType:
                     requestFile = RequestBody.create(MediaType.parse(MimeTypeConst.pdfMimeType),
                            imageDataList.get(i));
                    fileName = "attachment" + i + ".pdf";
                    body = MultipartBody.Part.createFormData("image", fileName, requestFile);
                    break;
            }
            parts.add(body);
        }
        uploadAttachment(parts);
    }