spring boot + axios 上传文件

1.引入第三方jar

//模板文件,可选
implementation 'org.springframework.boot:spring-boot-starter-freemarker'

2.简单案例,controller层创建接口

  /**
     * 上传文件
     *
     * @param files 文件对象
     * @param request req
     * @return R文件为响应结果自定义对象
     */
    @PostMapping("/admin/upload")
    public R upload(MultipartFile[] files, HttpServletRequest request) {
        for (MultipartFile file : files) {
            String filePath = request.getSession().getServletContext().getRealPath("/data/template/");
            log.info("filePath:{}", filePath);
            File saveFile = new File(filePath);
            try {
                if (!saveFile.isDirectory()) {
                    saveFile.mkdirs();
                }
                file.transferTo(new File(saveFile, file.getOriginalFilename()));
               //将文件复制当前项目目录
                File file1 = new File(filePath + file.getOriginalFilename());
                File file2 = new File("data/templates/" + file.getOriginalFilename());
                FileUtils.copyFile(file1, file2);
            } catch (IOException e) {
                log.error("找不到文件:{}", e.getMessage());
            }
        }
        return R.ok();
    }	
//R类
//如没有安装Lombok插件,请手动创建get、set
@Data
public class R {


    private Boolean success;

    private Integer code;

    private String message;

    private Map<String, Object> data = new HashMap<String, Object>();

    //把构造方法私有
    private R() {}

    //成功静态方法
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(200);
        r.setMessage("成功");
        return r;
    }

    //失败静态方法
    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(201);
        r.setMessage("失败");
        return r;
    }

    public R success(Boolean success){
        this.setSuccess(success);
        return this;
    }

    public R message(String message){
        this.setMessage(message);
        return this;
    }

    public R code(Integer code){
        this.setCode(code);
        return this;
    }

    public R data(String key, Object value){
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> map){
        this.setData(map);
        return this;
    }
}

3.前端页面

//html代码
<input type="file" id="files" name="files" multiple>
<input type="button" id="btn_upload" name="btn_upload" value="上传">
//JS代码
$("#btn_upload").click(() => {
        let files = $('#files').get(0).files[0]
        let form_data = new FormData()
        form_data.append("files", files)
        let config = {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
        axios.post(URL + apiUpload, form_data,config).then(res => {
            let data = res.data
            if (data.code === 200) {
                $("#tip").text("成功!")
            }
        }).catch(res => {
            $("#tip").text("失败!")
        })
    })

Q.E.D.


这个人很懒,什么都没有写