使用进度条进行改造文件上传在android中无效

时间:2015-08-07 05:08:16

标签: android file-upload progress-bar retrofit percentage

在我的应用程序中,我使用Retrofit将文件上传到服务器。现在我想显示进度条中文件上传的百分比。我找到了这个link的解决方案。

但进度条会快速填充每个不同大小的文件。我认为这个进展并不是上传到服务器的实际数据量。对于这个问题,Retrofit还有其他解决方案吗?我还检查了this

是否有可能在Retrofit ..?

请参阅我的代码

这是自定义类型文件

public class CountingTypedFile extends TypedFile {

    private static final int BUFFER_SIZE = 4096;

    private final ProgressListener listener;

    public CountingTypedFile(String mimeType, File file, ProgressListener listener) {
        super(mimeType, file);
        this.listener = listener;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        byte[] buffer = new byte[BUFFER_SIZE];
        FileInputStream in = new FileInputStream(super.file());
        long total = 0;
        try {
            int read;
            while ((read = in.read(buffer)) != -1) {
                total += read;
                out.flush();
                this.listener.transferred(total);
                out.write(buffer, 0, read);
            }
        } finally {
            in.close();
        }
    }
}

这是我在AsyncTask的dobackground中执行的代码部分

Uri myUri = Uri.parse(mImgUri);
            File file = new File(AppUtils.getRealPathFromURI(context, myUri));
            totalSize = file.length();
            RestAdapter restAdapter = new RestAdapter.Builder()
                    .setEndpoint(Constants.BASE_URL)
                    .setLogLevel(RestAdapter.LogLevel.BASIC)
                    .setClient(new OkClient(new OkHttpClient()))
                    .build();
            RetrofitCommonService mRetrofitCommonService = restAdapter.create(RetrofitCommonService.class);
            Log.d("TAG", "File is not null when converting from bitmap");

            TypedFile fileToSend  = new CountingTypedFile("image/png", file, new ProgressListener() {
                @Override
                public void transferred(long num) {
                    publishProgress((int) ((num / (float) totalSize) * 100));
                }
            });

            ImageUploadResponse imageUploadResponse = mRetrofitCommonService.upLoadImage(new AppUtils(context).getPhone(),
                    AppUtils.getDeviceId(context), fileToSend);

这是我的Retrofit服务

@Multipart
@POST("/user/asset")
@Headers("Accept:application/json")
ImageUploadResponse upLoadImage(@Header("mobile-number") String mPhone, @Header("uid") String imei,
                                @Part("file") TypedFile mBody);

0 个答案:

没有答案