基本上,我使用multipart/form-data
和retrofit2
一次将多张图片上传到服务器。但是奇怪的是,即使在压缩了图像大小之后,为什么要将它们上传到服务器也要花很长时间。意味着上传26 seconds
的10张图片几乎要花938 kb
。服务器的上传速度很好,因为当我上传2或3张照片时,它们的上传速度如此之快,但我不明白为什么会发生这种情况。所以,我应该一张一张地上传照片吗?我要解决这个问题吗?
接口:
public interface FileUploadService {
@Multipart
@POST("upload")
Call<ResponseBody> uploadMultipleFiles(
@Part("description") RequestBody description,
@Part MultipartBody.Part file1,
@Part MultipartBody.Part file2);
}
上传课程:
@NonNull
private RequestBody createPartFromString(String descriptionString) {
return RequestBody.create(
okhttp3.MultipartBody.FORM, descriptionString);
}
@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
File file = FileUtils.getFile(this, fileUri);
// creating RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
file
);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(),
requestFile);
}
public void upload(){
Uri file1Uri = ... // get it from a file chooser or a camera intent
Uri file2Uri = ... // get it from a file chooser or a camera intent
// create upload service client
FileUploadService service =
ServiceGenerator.createService(FileUploadService.class);
// create part for file (photo, video, ...)
MultipartBody.Part body1 = prepareFilePart("video", file1Uri);
MultipartBody.Part body2 = prepareFilePart("thumbnail", file2Uri);
// adding another part within the multipart request
RequestBody description = createPartFromString("hello, this is description
speaking");
// finally, execute the request
Call<ResponseBody> call = service.uploadMultipleFiles(description, body1,
body2);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call,
Response<ResponseBody> response) {
Log.v("Upload", "success");
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Upload error:", t.getMessage());
}
});
}