SpringBoot 上传文件功能

时间:2023-03-10 04:55:38
SpringBoot 上传文件功能

注意事项:

  springboot默认有以下文件配置要求, 可以自行在配置文件里面修改


spring:
servlet:
multipart:
enabled: true #是否处理上传
max-file-size: 1MB #允许最大的单个上传大小,单位可以是kb
max-request-size: 10MB #允许最大请求大小
package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile; import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID; @Controller
public class FileUploadController { /**
* 因为最终项目会打成jar包,所以这个的路径不能是jar包里面的路径
* 可以使用其他路径,比如上传到F盘下的upload文件夹下 写成:F:/upload/
*/
private String fileUploadPath = ""; /**
* 文件上传,具体逻辑可以自行完善
*
* @param file 前端表单的name名
* @return w
*/
@PostMapping("/upload")
@ResponseBody
public String upload(MultipartFile file) { if (file.isEmpty()) {
//文件空了
return null;
} //文件扩展名
String extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); //使用UUID生成文件名称
String fileName = UUID.randomUUID().toString() + extName; //文件上传的全路径
String filePath = fileUploadPath + fileName; File toFile=new File(filePath); if (!toFile.getParentFile().exists()){
//文件夹不存在,先创建文件夹
toFile.getParentFile().mkdirs();
}
try {
//进行文件复制上传
FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(toFile));
} catch (Exception e) {
//上传失败
e.printStackTrace();
}
//返回文件所在绝对路径
return filePath; } }

然后添加个配置就可以把路径映射出去

@Configuration
public class webMvcConfigurerAdapter implements WebMvcConfigurer {
/**
* 配置静态访问资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**").addResourceLocations("classpath:/path/");
}
}
  • addResoureHandler:指的是对外暴露的访问路径
  • addResourceLocations:指的是内部文件放置的目录(如果在项目下 可以配置成    file:/path/)