有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓改型中上传文件时显示进度条

我正在开发一款使用改型的安卓应用程序。我想上传任何类型的文件到我的服务器参数。例如,在我的应用程序中有文本字段,如电子邮件和文件上载字段。当我输入字段并单击提交按钮时。它显示上载文件并将文件和数据发送到服务器的百分比。当上传过程进行时,它希望显示完成文件的百分比。怎么可能呢? 有没有参考网站或教程? 请帮帮我


共 (1) 个答案

  1. # 1 楼答案

    创建此接口

    public interface ProgressListener {
                    void transferred(long num);
                }
    

    这个班呢

        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.write(buffer, 0, read);
    
                        try{
                            if (this.listener != null)
                                this.listener.transferred(total);
                        }catch (Exception e){
    
                        }
    
                    }
                } finally {
                    in.close();
                }
            }
        }
    

    定义此方法

    @POST("/{path}")
        public JsonObject makeRequestForAttachmentsUpload(@Path(value = "path", encode = false) String path, @Body MultipartTypedOutput multipartTypedOutput);
    

    然后像这样调用upload方法

        RestClient restClient = new RestClient();
        ApiService apiService = restClient.getApiService();
    
    MultipartTypedOutput multipartTypedOutput = new MultipartTypedOutput();
        // add and string parameters            
        for (String key : requestParams.keySet()) {
                        multipartTypedOutput.addPart(key, new TypedString(requestParams.get(key)));
                    }
    
        // add attchments
                    multipartTypedOutput.addPart(attachmentName, new CountingTypedFile(attachmentType, new File(attachmentPath), listener));
    apiService.makeRequestForAttachmentsUpload(requestName, multipartTypedOutput);
    

    并通过定义此侦听器来侦听进度

    listener = new DPAPIService.ProgressListener() {
                    @Override
                    public void transferred(long num) {
                        publishProgress(((num / (float) fileSize)));
                    }
            };