用AJAX异步提交表单上传多个文件(type=‘file‘)案例

    因为在框架中上传文件时不适合直接用form提交,因为这样会刷新页面。我们一般会用ajax进行异步上传。此方法可上传多种类型文件。

    html代码:

    注意如果要多选文件需要在input上增加属性 multiple="multiple"

    js:

function uploadTrainProduct(){
    var formData = new FormData($("#form1")[0]);  //重点:要用这种方法接收表单的参数
    $.ajax({
        url : "/it/orderManage/uploadTrainProduct",
        type : 'POST',
        data : formData,
        // 告诉jQuery不要去处理发送的数据
        processData : false,                 
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        async : false,
        success : function(data) {
            if(data){
            }
        }
    });
}

    java代码:

@RequestMapping(value = "/uploadTrainProduct", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
    @ResponseBody
    public String uploadTrainProduct(
            @RequestParam(value = "file") MultipartFile[] files,  //这样接收文件
            @RequestParam(value = "id") String id,            //接收其他参数
            @RequestParam(value = "content") String content,
            HttpServletRequest request
    ) {
        try {
            for (MultipartFile file : files) {    //循环保存文件
                uploadFile(file, request);
            }
            // 返回前台
            return "success";

        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }

    }

    public String uploadFile(MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        String path="d:/images/m2";            //设置文件保存路径
//        File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName));
        File tempFile = new File(path, String.valueOf(fileName));
        if (!tempFile.getParentFile().exists()) {    //创建文件夹
            tempFile.getParentFile().mkdir();
        }
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        file.transferTo(tempFile);
        return "images/" + tempFile.getName();
    }
可以试试,非常好用

你可能感兴趣的:(前端,表单提交多个文件,ajax提交表单)