springboot 上传文件保存在本地磁盘

1.修改application.properties配置文件,设置保存磁盘地址(方便以后修改)

upload.path = /Users/myname/Documents/upload/

地址自定义即可,这是我本机地址,Windows可设置:d:\\upload 自定义即可

2.创建ApiController

@RestController
@RequestMapping(value = "/api")
public class ApiController {

    @Value("${upload.path}") private String uploadPath;

    @RequestMapping(value = "/uploads", method = RequestMethod.POST)
    public @ResponseBody
    String uploads(HttpServletRequest request, MultipartFile[] file) {
        String filename = "";
        try {
            //上传目录地址
            String uploadDir = uploadPath;

            //如果目录不存在,自动创建文件夹
            File dir = new File(uploadDir);

            if (!dir.exists()) {
                dir.mkdir();
            }

            //遍历文件数组执行上传
            for (int i = 0; i < file.length; i++) {
                if (file[i] != null) {
                    //调用上传方法
                    filename = executeUpload(uploadDir, file[i]);
                }
            }
        } catch (Exception e) {
            //打印错误堆栈信息
            e.printStackTrace();
            return "上传失败";
        }
        return filename;
    }

    private String executeUpload(String uploadDir, MultipartFile file) throws Exception {
        //文件后缀名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //上传文件名
        String filename = UUID.randomUUID() + suffix;
        //服务器端保存的文件对象
        File serverFile = new File(uploadDir + filename);

        if(!serverFile.exists()) {
        //先得到文件的上级目录,并创建上级目录,在创建文件
            serverFile.getParentFile().mkdir();
            try {
                //创建文件
                serverFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将上传的文件写入到服务器端文件内
        file.transferTo(serverFile);

        return filename;
    }
}

3.前端ajax提交问题即可:

uploadFile(event){//上传文件
	const _this=this;
	let formData=new FormData();
	let _file = event.target.files[0];
	let size = _file.size;
	let maxsize = 4*1024*1024;//4M  
	if(size > maxsize){
		$("#uploadbox").addClass("error");
		this.clearInput();
		return;
	}
	formData.append('file',_file);
	$.ajax({
		type: "POST",
		url:  "/api/uploads",
		data: formData,
		contentType:"application/json",
		processData:false,
		contentType:false,
		async: true,
		success: function(data) {
			console.log(data)
						
		},
		error: function(data) {
			console.log(data)
		}
	});			
}

 

你可能感兴趣的:(springboot)