使用retrofit上传PDF和图像文件



我的手机应用程序上传PDF文件和图像文件到服务器。我可以使用下面的代码上传图像文件。

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

从存储器中选择任意图像文件

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

构建多部分主体部分请求。

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