spring boot springmvc上传进度条

来源:互联网 发布:视频剪辑for mac 编辑:程序博客网 时间:2024/05/16 18:45

网上很多人对于这个点点太令色,所以我把代码都发上来



直接上源码:

package com.gwtjs.icustom.attachments;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartResolver;

import com.gwtjs.icustom.attachments.resolver.CustomMultipartResolver;

@EnableAutoConfiguration(exclude = {MultipartAutoConfiguration.class})

@Configuration
@ComponentScan(basePackages = {"com.gwtjs.icustom.attachments"})
@ServletComponentScan(basePackages = {"com.gwtjs.icustom.attachments"})
@SpringBootApplication
public class UploadfileTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(UploadfileTestApplication.class, args);
    }
    
    /*
     * 将 multipartResolver 指向我们刚刚创建好的继承 CommonsMultipartResolver 类的自定义文件上传处理类
     */
    @Bean(name = "multipartResolver")
    public MultipartResolver multipartResolver() {
        CustomMultipartResolver customMultipartResolver = new CustomMultipartResolver();
        return customMultipartResolver;
    }
    
}

package com.gwtjs.icustom.attachments.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/attachments")
public class UploadController {

    @RequestMapping(value = "/showUpload", method = RequestMethod.GET)
    public ModelAndView showUpload() {
        return new ModelAndView("/UploadProgressDemo");
    }

    @RequestMapping("/upload")
    @ResponseBody
    public void uploadFile(MultipartFile file) {
        System.out.println(file.getOriginalFilename());
    }
    
    @RequestMapping("/uploads")
    @ResponseBody
    public Map<String,Object> uploadFiles(HttpServletRequest request) {
        Map<String,Object> result = new HashMap<String,Object>();
        List<MultipartFile> files2 = ((MultipartHttpServletRequest) request).getFiles("file");
        BufferedOutputStream stream = null;
        String uploadPath = "upload/zip/";
        result.put("fileLength", files2.size());
        int i = 0;
        for (MultipartFile file : files2) {
            String originalFilename = file.getOriginalFilename();
            i++;
            validateType(uploadPath);
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(uploadPath,originalFilename)));
                    stream.write(bytes);
                    result.put("file"+i, uploadPath+originalFilename);
                    stream.close();
                } catch (Exception e) {
                    result.put("message", originalFilename+"You failed to upload  => " + e.getMessage());
                }
            } else {
                result.put("message", originalFilename+"You failed to upload  because the file was empty.");
            }
        }
        return result;
    }
    
    /**
     * 验证上传的文件类型
     * @return
     */
    private Map<String,Object> validateType(String path){
        Map<String,Object> result = new HashMap<String,Object>();
        File file = new File(path);
        if(!file.exists())
            file.mkdirs();
        return result;
    }
    
    /**
     * 验证上传的文件路径,没有则创建
     * @return
     */
    private Map<String,Object> validatePath(String path){
        Map<String,Object> result = new HashMap<String,Object>();
        File file = new File(path);
        if(!file.exists())
            file.mkdirs();
        return result;
    }

}


package com.gwtjs.icustom.attachments.entity;

import org.springframework.stereotype.Component;

@Component
public class ProgressEntity {
    private long pBytesRead = 0L; // 到目前为止读取文件的比特数
    private long pContentLength = 0L; // 文件总大小
    private int pItems; // 目前正在读取第几个文件

    public long getpBytesRead() {
        return pBytesRead;
    }

    public void setpBytesRead(long pBytesRead) {
        this.pBytesRead = pBytesRead;
    }

    public long getpContentLength() {
        return pContentLength;
    }

    public void setpContentLength(long pContentLength) {
        this.pContentLength = pContentLength;
    }

    public int getpItems() {
        return pItems;
    }

    public void setpItems(int pItems) {
        this.pItems = pItems;
    }

    @Override
    public String toString() {
        float tmp = (float) pBytesRead;
        float result = tmp / pContentLength * 100;
        return "ProgressEntity [pBytesRead=" + pBytesRead + ", pContentLength=" + pContentLength + ", percentage="
                + result + "% , pItems=" + pItems + "]";
    }
}

package com.gwtjs.icustom.attachments.listener;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.ProgressListener;
import org.springframework.stereotype.Component;

import com.gwtjs.icustom.attachments.entity.ProgressEntity;

@Component
public class UploadProgressListener implements ProgressListener {

    private HttpSession session;

    public void setSession(HttpSession session) {
        this.session = session;
        ProgressEntity status = new ProgressEntity();
        session.setAttribute("status", status);
    }

    /*
     * pBytesRead 到目前为止读取文件的比特数 pContentLength 文件总大小 pItems 目前正在读取第几个文件
     */
    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        ProgressEntity status = (ProgressEntity) session.getAttribute("status");
        status.setpBytesRead(pBytesRead);
        status.setpContentLength(pContentLength);
        status.setpItems(pItems);
    }
}

package com.gwtjs.icustom.attachments.resolver;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
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.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.gwtjs.icustom.attachments.listener.UploadProgressListener;

public class CustomMultipartResolver extends CommonsMultipartResolver {

    @Autowired
    private UploadProgressListener uploadProgressListener;

    @Override
    protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
        String encoding = determineEncoding(request);
        FileUpload fileUpload = prepareFileUpload(encoding);
        uploadProgressListener.setSession(request.getSession());// 问文件上传进度监听器设置session用于存储上传进度
        fileUpload.setProgressListener(uploadProgressListener);// 将文件上传进度监听器加入到 fileUpload 中
        try {
            List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
            return parseFileItems(fileItems, encoding);
        } catch (FileUploadBase.SizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
        } catch (FileUploadBase.FileSizeLimitExceededException ex) {
            throw new MaxUploadSizeExceededException(fileUpload.getFileSizeMax(), ex);
        } catch (FileUploadException ex) {
            throw new MultipartException("Failed to parse multipart servlet request", ex);
        }
    }

}

测试页面:


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Upload Files using XMLHttpRequest - Minimal</title>

</head>
<body>
    <form id="upload_form1" enctype="multipart/form-data" method="post"
        action="/attachments/upload">
        <div align="center">
            <span class="btn btn-success fileinput-button"> <span>上传</span>
                <input type="file">
            </span>
        </div>
        <div class="upload_row_layout">
            <div class="input_row">
                <label for="file">Select a File to Upload</label><br /> <input
                    tarIndex="1" class="atta_file_input" type="file" name="file"
                    onchange="fileSelected(this);" />
            </div>
            <div class="input_info_row">
                <div class="fileName" id="file1_name"></div>
                <div class="fileSize" id="file1_size"></div>
                <div class="fileType" id="file1_type"></div>
            </div>
        </div>
        <div class="upload_row_layout">
            <div class="input_row">
                <label for="file">Select a File to Upload</label><br /> <input
                    tarIndex="2" class="atta_file_input" type="file" name="file"
                    onchange="fileSelected(this);" />
            </div>
            <div class="input_info_row">
                <div class="fileName" id="file2_name"></div>
                <div class="fileSize" id="file2_size"></div>
                <div class="fileType" id="file2_type"></div>
            </div>
        </div>
        <div class="progressNumber" id="file_progress">
            <div class="progressContent" id="progressContent"></div>
        </div>
        <div class="row">
            <input type="button" onclick="uploadFile()" value="Upload" />
        </div>

    </form>

    <script type="text/javascript">
        function getFileType(fileName) {
        }

        function fileSelected(node) {
            var tarIndex = node.getAttribute('tarIndex');
            console.warn(tarIndex, node);
            var file = node.files[0];
            console.warn(file);
            if (file) {
                var fileSize = 0;
                if (file.size > 1024 * 1024) {
                    fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100)
                            .toString()
                            + 'MB';
                } else {
                    fileSize = (Math.round(file.size * 100 / 1024) / 100)
                            .toString()
                            + 'KB';
                }
                //console.warn(node.parentNode.parentNode);
                document.getElementById('file' + tarIndex + '_name').innerHTML = 'Name: '
                        + file.name;
                document.getElementById('file' + tarIndex + '_size').innerHTML = 'Size: '
                        + fileSize;
                document.getElementById('file' + tarIndex + '_type').innerHTML = 'Type: '
                        + file.type;
            }
        }

        function uploadFile() {
            var form = document.getElementById('upload_form1');
            var tagElements = document.getElementsByTagName('input');

            var fd = new FormData();
            for (var j = 0; j < tagElements.length; j++) {
                var ele = tagElements[j];
                if ('file' === ele.type) {
                    console.info(ele.type);
                    fd.append("file", ele.files[0]);
                }
            }
            console.warn(fd);
            fd.append("createDate", new Date());

            var xhr = new XMLHttpRequest();
            xhr.upload.addEventListener("progress", uploadProgress, false);
            xhr.addEventListener("load", uploadComplete, false);
            xhr.addEventListener("error", uploadFailed, false);
            xhr.addEventListener("abort", uploadCanceled, false);
            xhr.open("POST", "/attachments/uploads");
            xhr.send(fd);
        }

        function uploadProgress(evt) {
            if (evt.lengthComputable) {
                var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                document.getElementById('progressContent').style.width = percentComplete.toString()+ '%';
                document.getElementById('progressContent').innerHTML = percentComplete.toString()+ '%';
            } else {
                document.getElementById('file_progress').innerHTML = '无法计算';
            }
        }

        function uploadComplete(evt) {
            /* 当服务器响应后,这个事件就会被触发 */
            alert("上传成功:" + evt.target.responseText);
        }

        function uploadFailed(evt) {
            alert("上传失败:" + "上传文件发生了错误");
        }

        function uploadCanceled(evt) {
            alert("上传取消:" + "上传被用户取消或者浏览器断开连接");
        }
    </script>
    
    <style type="text/css">
    .progressNumber{width:100%;height:22px;line-height:22px;border:1px solid #369;margin:3px auto;}
    .progressContent{width:1px;height:22px;line-height:22px;background:#D2D41A;margin:0;}
    
.atta_file_input {
    width: 368px;
    height: 26px;
    background: #336699;
    border: 1px solid #AAA;
    line-height: 26px;
}

.fileinput-button {
    position: relative;
    display: inline-block;
    overflow: hidden;
}

.fileinput-button input {
    position: absolute;
    right: 0px;
    top: 0px;
    opacity: 0;
    -ms-filter: 'alpha(opacity=0)';
    font-size: 200px;
}
</style>
</body>
</html>



不限制文件大小,不限制文件类型,重点是html5的事件监听,多文件的进度条稍后补充。
























原创粉丝点击