• apache fileupload 文件上传,及文件进度设置获取


    文件上传action处理:

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                DiskFileItemFactory factory = new DiskFileItemFactory();
                factory.setSizeThreshold(2048);
                // 设置临时文件路径,通过设置临时文件可以在上传大文件时候达到多少先写入临时文件,不会造成卡死情况
                String tempPath = "/mnt/disk1/tomcat/tomcat1/upload/tmp/";
                File tempFile = new File(tempPath);
                if (!tempFile.exists())
                    tempFile.mkdirs();
                factory.setRepository(tempFile);
                ServletFileUpload upload = new ServletFileUpload(factory);
           //设置可上传文件大小 
                upload.setSizeMax(1024000000);
            //设置文件进度监听器
                UploadProgressListener progressListener = new UploadProgressListener();
            //放入session中,下次访问可以取出,获取文件进度
                session.setAttribute("progress", progressListener);
                upload.setProgressListener(progressListener);
                List<FileItem> fileldItems = null;
                try {
                    fileldItems = upload.parseRequest(request);
                } catch (FileUploadException e1) {
                    e1.printStackTrace();
                }
                Map<String, String> fieldMap = new HashMap<String, String>();
                List<FileItem> fileList = new ArrayList<FileItem>();
                Iterator<FileItem> iter = fileldItems.iterator();
                StringBuffer url = new StringBuffer("request=");
                url.append(request.getRequestURI());
                while (iter.hasNext()) {
                    FileItem item = iter.next();
              //获取非文件字段
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = item.getString();
                        url.append("&" + name + "=" + value);
                        fieldMap.put(name, value);
                    } else {
                        fileList.add(item);
                    }
                }
          //记录非文件字段
                logger.error(url.toString().replaceFirst("&", "?"));
                    for (FileItem item : fileList) {
                        String fileName = item.getName();
                        if (fileName == null || fileName.equals(""))
                            continue;
                        fileName = fileName
                                .substring(fileName.lastIndexOf("\") + 1);
                        String ext = fileName.substring(fileName.lastIndexOf("."));
                        fileName = fileName.substring(0, fileName.lastIndexOf("."));
                        String dateStr = DateUtil.formatDate(new Date(),
                                "yyyyMMddHHmmss");
                        String filename = fileName + "_" + dateStr + ext;
                        String filePath = "";
                        filePath = "/mnt/disk1/tomcat/tomcat1/upload/files/"
                                + DecoderUtil.toChinese(fieldMap.get("user"));
                        File fp = new File(filePath);
                        if (!fp.exists())
                            fp.mkdirs();
                        File uploadedFile = new File(fp, filename);
                        try {
                            item.write(uploadedFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                  }
    ProgressListener:由于我这个不只记录了文件进度,还有别的信息,懒得删了,就这样黏上来了,可以根据情况自己修改。
    package lbi.flow.util;
    
    import java.text.DecimalFormat;
    
    import org.apache.commons.fileupload.ProgressListener;
    
    public class UploadProgressListener implements ProgressListener {
        private long megaBytes = -1;
        private long readBytes = 0;
        private long totalBytes = 0;
        private long processedCount = 0;
        private long totalCount = 0;
        private String speed = "0";// k/s
        private long starttime;
        private int step = 1;
    
        private final DecimalFormat df = new DecimalFormat("0.##%");
        private final DecimalFormat df2 = new DecimalFormat("0.##");
    
        public UploadProgressListener() {
            this.starttime = (long) System.currentTimeMillis();
        }
    
        public String getProgress() {
            if (this.step == 1)
                return df.format(this.readBytes * 1.0 / this.totalBytes);
            else
                return df.format(this.processedCount * 1.0 / this.totalCount);
        }
    
        public String getOverallProgress() {
            if (this.step == 1)
                return df.format(this.readBytes * 1.0 / this.totalBytes / 3);
            else
                return df.format(this.processedCount * 1.0 / this.totalCount / 3
                        + (this.step - 1) * 1.0 / 3);
        }
    
        public void update(long pBytesRead, long pContentLength, int pItems) {
            long mBytes = pBytesRead / 1000000;
            if (megaBytes == mBytes && pBytesRead != pContentLength) {
                return;
            }
            megaBytes = mBytes;
            long deadline = System.currentTimeMillis();
            speed = df2.format(pBytesRead / 1024
                    / ((deadline - starttime) * 1.0 / 1000));
            readBytes = pBytesRead;
            totalBytes = pContentLength;
        }
    
        public long getProcessedCount() {
            return processedCount;
        }
    
        public void setProcessedCount(long processedCount) {
            this.processedCount = processedCount;
        }
    
        public long getTotalCount() {
            return totalCount;
        }
    
        public void setTotalCount(long totalCount) {
            this.totalCount = totalCount;
        }
    
        public int getStep() {
            return step;
        }
    
        public void setStep(int step) {
            this.step = step;
        }
    
        public String getSpeed() {
            return this.speed;
        }
    }

    这样,再写一个接口,通过session获取存储的ProgressListener即可获取上传文件的进度,可以支持多文件上传的。

  • 相关阅读:
    MYSQL中排序
    编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary)
    job1
    python中对于数组的操作
    python中将字符串转为字典类型
    python中的周几
    python 链接redis 获取对应的值
    jenkins 设置定时任务规则
    如何安全close go 的channel
    [转]
  • 原文地址:https://www.cnblogs.com/lcxdever/p/3730596.html
Copyright © 2020-2023  润新知