基于springboot的ajax异步文件上传

原文链接:https://blog.csdn.net/Yaphst/article/details/82625159

input选项

  input可以不写在form中,从而也就不需要添加enctype=”multipart/form-data” 和method=”post”,这里我们直接写一个input.

<input id="cert" type="file" />
<input type="button" value="上传" οnclick="submit2();" />

ajax提交

function submit2(){
    var type = "file";          //后台接收时需要的参数名称,自定义即可
    var id = "cert";            //即input的id,用来寻找值
    var formData = new FormData();
    formData.append(type, $("#"+id)[0].files[0]);    //生成一对表单属性
    $.ajax({
        type: "POST",           //因为是传输文件,所以必须是post
        url: '/upload',         //对应的后台处理类的地址
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
            alert(data);
        }
    });
}

springboot后台接收

接收文件我们这里使用的是MultipartFile这个类,通过搭配注解写到方法的参数里即可。有一点要注意的是,有些浏览器(如IE)在提交文件后,后台得到的文件名是当时在该浏览器中选择文件时的全路径,这里需要在方法里处理一下,否则保存文件时会报错。
@RequestParam(“file”)中的参数字符串”file”就是前面在dataForm中定义过的,这里就可以用MultipartFile接收此参数对应的文件。

@Controller
public class UploadController {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if(fileName.indexOf("\") != -1){
            fileName = fileName.substring(fileName.lastIndexOf("\"));
        }
        String filePath = "src/main/resources/static/files/";
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(filePath+fileName);
            out.write(file.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
        return "上传成功!";
    }
}
原文地址:https://www.cnblogs.com/ssyh/p/12334897.html