当前位置: 移动技术网 > IT编程>开发语言>Java > springboot实现文件上传实时进度(单文件)

springboot实现文件上传实时进度(单文件)

2020年07月16日  | 移动技术网IT编程  | 我要评论

1.pom.xml文件中导入包。

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

2.在配置文件中对上传文件的参数进行配置

resource.path=xx/xx/xx/xx/(写你自己要上传文件到的文件夹路径)

还可以配置允许上传的最大文件数等配置,需要的话百度一下。

3.编写配置类

FileUploadProgressListener.java

思路是把文件上传的进度在后台算出来,存在session中,前台定时任务一直请求后台将进度实时返回。

import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;
 
import javax.servlet.http.HttpSession;
 
@Component
public class FileUploadProgressListener implements ProgressListener {
 
    private HttpSession session;
 
    public void setSession(HttpSession session) {
        this.session = session;
        session.setAttribute("upload_percent", 0);
    }
 
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        int percent = (int) (pBytesRead * 100.0 / pContentLength);
        session.setAttribute("upload_percent", percent);
    }
}

CustomMultipartResolver.java

 import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
 
import javax.servlet.http.HttpServletRequest;
import java.util.List;
 
public class CustomMultipartResolver extends CommonsMultipartResolver {
 
    @Autowired
    private FileUploadProgressListener listener;
 
    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
 
        fileUpload.setProgressListener(listener);
        listener.setSession(request.getSession());
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        }catch (FileUploadException ex) {
            throw new MultipartException("Failed to parse multipart servlet request", ex);
        }
    }
}

BeanConfig.java

import com.demo.jin.demo.config.CustomMultipartResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;
 
@Configuration
public class BeanConfig {
 
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver()
    {
        return new CustomMultipartResolver();
    }
}

上面这几个配置类都是要用到 commons-fileupload需要的,百度一下,大同小异。

controller层

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;
 
@Controller
public class fileuploadController {
 
    @Value("${resource.path}")
    private String resourcePath; //配置的上传路径
    private static final Logger logger = LoggerFactory.getLogger(fileuploadController.class);
 
     /**
      * 上传文件的页面
      * @return
      */
    @RequestMapping(value = "/uploadPage")
    public String uploadPage(){
        return "uploadPage";
    }

    /**
     * 处理文件上传
   */
 @RequestMapping(value="/upload", method = RequestMethod.POST)
 @ResponseBody
 public String uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
         Calendar cal = Calendar.getInstance();
         Integer year = cal.get(Calendar.YEAR);
         Integer month = cal.get(Calendar.MONTH)+1;
         Integer day = cal.get(Calendar.DAY_OF_MONTH);
         String msg = "SUCCESS";
         String fileName = file.getOriginalFilename();
           //该路径可以从文件中读取,此处演示略
         String filePath = resourcePath + File.separator + year + File.separator + month + File.separator + day + File.separator;
         System.out.println("上传路径:"+filePath);
         try {
             uploadFile(file.getBytes(), filePath, fileName);
         } catch (Exception e) {
             msg = e.getMessage();
         }
         //返回json
         return msg;
     }

    /**
    * @Description : 上传文件
    * @param file : 文件实体
    * @param filePath : 文件目标路径
    * @param fileName : 文件名
    * @throws Exception
    */
   public void uploadFile(byte[] file, String filePath, String fileName) throws Exception { 
             File targetFile = new File(filePath);  
             if(!targetFile.exists()){ 
                 targetFile.mkdirs(); 
            }
             FileOutputStream out = new FileOutputStream(filePath+fileName);
             out.write(file);
             out.flush();
             out.close();
     }

    @RequestMapping(value = "/uploadStatus")
    @ResponseBody
    public Integer uploadStatus(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object percent = session.getAttribute("upload_percent");
        return null != percent ? (Integer) percent : 0;
    }
}

 前台页面

uploadPage,html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8"></meta>
    <title>测试</title>
</head>
 <style type="text/css">
    #parent{border:1px #EEE solid;width: 500px;height: 30px;margin: 0 auto;}
    #child{width: 0%;height: 30px;background-color: lime;}
    p{text-align: center;color: fuchsia;}
    
    .file {
    position: relative;
    display: inline-block;
    background: #D0EEFF;
    border: 1px solid #99D3F5;
    border-radius: 4px;
    padding: 4px 12px;
    overflow: hidden;
    color: #1E88C7;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
}
.file input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
}
.file:hover {
    background: #AADFFD;
    border-color: #78C3F3;
    color: #004974;
    text-decoration: none;
}
    </style>
<body>
<form id="form" action="/upload" method="POST" enctype="multipart/form-data" οnsubmit="return upload();">
    <input type="file" name="file" class="file" />
    <br/>
    <input type="submit" value="提交"/>
     <p id="info"></p>
    <div id="parent">
        <div id="child"></div>
    </div>
</form>
</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery.form/4.2.2/jquery.form.min.js"></script>
<script>
    function upload() {
        $("#form").ajaxSubmit(function(message) {
 
        });
        // 100ms 打印一次当前的上传进度
        var update=setInterval(function () {
            var flag = false;
            $.ajax({
                type:"get",
                dataType: 'json',
                url:"/uploadStatus",
                success: function(result){
                     $("#info").text("正在上传:"+result+"%");
                     $("#child").width(result+"%");
                     if(result==100){
                         //清除定时器,停止更新
                         flag = true;
                         if(flag){
                             clearInterval(update);
                            console.log("恭喜,更新成功!");
                            $("#info").text("上传成功:"+result+"%");
                             }
                         }
                    console.log(result);
                }
            });
        }, 100);
        return false;
    }
</script>
</html>

样式都是网上找的。

只实现了单文件的上传,多文件的可以在这个基础上改一下。

本文地址:https://blog.csdn.net/TqingqingT/article/details/107354304

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网