使用html5的FromData对象可轻松实现文件异步上传,同时可以传递字符串参数

一般监听onchange事件执行上传动作,同时注意上传成功后将value置空,否则会出现在文件名不变的情况下无法重新上传

  • 前端
<form method="post" action="/component/upload" enctype="multipart/form-data">
    file: <input id="uploadFile" type="file" name="file" accept="text/html" onchange="handleFiles(this.files)">
</form>
    function handleFiles(files) {
        if(!files.length){
            alert('未选择文件')
            return;
        }
        var formData = new FormData();
//        var file = $("#uploadFile")[0].files[0];
        var file = files[0];
        formData.append("file", file);
        formData.append("key", "value");
        console.log(file.name);
        console.log(file.size);
        console.log(file.lastModifiedDate);
        $.ajax(
                {
                    url: '/component/upload',
                    type: 'POST',
                    data: formData,
                    contentType: false, //禁止设置请求类型
                    processData: false, //禁止jquery对DAta数据的处理,默认会处理
                    //禁止的原因是,FormData已经帮我们做了处理
                    success: function (result) {
                        $('#uploadFile').val('');
                        console.log(result);
                    }
                }
        );
    }
  • 服务端接收
    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam(value = "file", required = false) MultipartFile[] multipartFiles, String key, HttpServletRequest request) throws Exception{
        if(null == multipartFiles || multipartFiles.length < 1){
            return "no files received";
        }
        String dir = System.getProperty("java.io.tmpdir", "/tmp");
        logger.info("key: " + key);
        for (int i = 0; i < multipartFiles.length; i++) {
            MultipartFile f = multipartFiles[i];
            if(f.getSize() == 0L){
                logger.info("index: " + i + " 未选择文件");
                continue;
            }
            File file = new File(dir, f.getOriginalFilename());
            f.transferTo(file);
            logger.info("filename: {}, size: {}, write to path: {}", f.getOriginalFilename(), f.getSize(), file.getCanonicalPath());
        }
        return "view console";
    }

参考:

https://www.jianshu.com/p/d90d2e6bb0d5

https://developer.mozilla.org/zh-CN/docs/Web/API/FormData/Using_FormData_Objects