如何在 Android 应用中更快地上传图片?

编程入门 行业动态 更新时间:2024-10-11 03:22:44
本文介绍了如何在 Android 应用中更快地上传图片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在开发一个类似于 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-28 15:11:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1174858.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:更快   上传图片   如何在   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!