问题
I am developing an Android app which is like OLX, allowing the user to add ads and course select images from gallery to upload onto my server. But uploading large images takes a long time.
How can I fix this issue?
I am using Volley library for uploading the images. Are there any better libraries?
回答1:
use this
Retrofit retrofit = new Retrofit.Builder().client(okHttpClient).baseUrl(domain)
.addConverterFactory(GsonConverterFactory.create()).build();
Service service = retrofit.create(Service.class);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
final MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
final RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());
Call<ServerResponse> upload = service.uploadFile(fileToUpload, filename);
upload.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, final Response<ServerResponse> response) {
final ServerResponse serverResponse = response.body();
if (serverResponse.getSuccess()) {
//Handle Response
}
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
if(t instanceof SocketTimeoutException){
Toast.makeText(getApplicationContext(), "Unable To Upload\nError: Socket Time out. Please try again", Toast.LENGTH_LONG).show();
}
t.printStackTrace();
}
});
Service Interface
public interface Service {
@Multipart
@POST("path/upload.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
回答2:
Your question is quite broad, but here are some ideas:
- Resize your images to a smaller size: the user might upload 12-16 megapixel images, but 1920x1080 is usually more than enough, which is only ~2 megapixels, a lot smaller.
- Use a different format with lossy compression: a 75% quality JPEG picture is almost indistinguishable from a 100%, while it can be 2 or 3 times smaller in size.
- Increase buffer size for the request: Higher buffer sizes lead to less packets, which means faster uploads. Although if the user has a very bad connection (packet loss very high), smaller packets can be sometimes faster.
You will see high performance gains with the first two points, you might only see a bit of improvement with the last point if you are very far from the server geographically.
来源:https://stackoverflow.com/questions/42733731/how-to-make-images-upload-faster-in-an-android-app