如何在 Android 应用中更快地上传图片? [英] How to make images upload faster in an Android app?

查看:45
本文介绍了如何在 Android 应用中更快地上传图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个类似于 OLX 的 Android 应用程序,允许用户添加广告并从图库中选择图片上传到我的服务器.但是上传大图片需要很长时间.

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?

我正在使用 Volley 库 上传图片.有没有更好的库?

I am using Volley library for uploading the images. Are there any better libraries?

推荐答案

使用这个

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

服务接口

public interface Service {
@Multipart
@POST("path/upload.php")
Call<ServerResponse> uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);

}

这篇关于如何在 Android 应用中更快地上传图片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆