SpringBoot文件上传 MultipartAutoConfiguration源码简单解析

SpringBoot中文件上传
老样子,先上代码,再源码分析

SpringBoot里自动装配了MultipartResolver
所以这样我们可以不用加依赖

文件上传类

@RestController
public class UploadController {
    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest req) throws IOException {
        String format = sdf.format(new Date());
        String realPath = req.getServletContext().getRealPath("/img") + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        String oldName = file.getOriginalFilename();
        String newNamme = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            file.transferTo(new File(folder, newNamme));
            String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newNamme;
            return url;


    }
}

这里需要讲一下的是

你可能感兴趣的:(SpringBoot)