更新记录
2021/1/1 1:00 am 单文件上传实现
2020/1/1 16:30 pm 多文件上传实现,前端跨与请求配置
需求
- 文件上传,返回一个url,使用url可以直接访问该资源
- 上传文件存放在本机非SprngBoot项目静态资源位置
- 多文件上传
- 解决跨与请求
实现
- 配置
application.yaml
定义一个存放上传文件的位置
web:
upload-path: /xxx/uploadFile/
单文件
- controller
@RestController
public class FileUploadController {
@Value("${web.upload-path}")
String fileDir;
@PostMapping("upload")
public Map upload(MultipartFile file, HttpServletRequest request){
String realPath = fileDir;
File folder= new File(realPath);
if (!folder.exists()){
folder.mkdirs();
}
String oldName=file.getOriginalFilename();
String newName= UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
Map<String,Object> result=new HashMap<>();
try {
file.transferTo(new File(folder,newName));
String url=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/file/"+newName;
result.put("status","ok");
result.put("url",url);
} catch (IOException e) {
result.put("status","failed");
result.put("msg",e.getMessage());
}
return result;
}
}
上面的controller会返回给用户一个类似于http://localhost:8080/file/xxx.jpg
还需要配置资源请求映射才能正常访问到该服务
- 配置静态资源映射
@Configuration
public class MyWebMvcConfig extends WebMvcConfigurationSupport {
@Value("${web.upload-path}")
private String uploadFilePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/**").addResourceLocations("file:"+uploadFilePath);
//这句不要忘了,否则项目默认静态资源映射会失效
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
多文件
@PostMapping("uploadMul")
public Map upload(MultipartFile[] files, HttpServletRequest request){
Map<String,Object> result=new HashMap<>();
int count=0;
List<Map<String,Object>> list=new ArrayList<>();
if (files==null|| files.length==0){
result.put("","failed");
result.put("msg","no file");
return result;
}
for (MultipartFile file : files) {
Map<String,Object> map=new HashMap<>();
Map res = upload(file, request);
map.put("name",file.getOriginalFilename());
Object url = res.get("url");
if (url!=null){
count++;
map.put("url",url);
map.put("status","ok");
}else {
map.put("status","failed");
map.put("msg",res.get("msg"));
}
list.add(map);
}
result.put("upload",files.length);
result.put("succeed",count);
result.put("detail",list);
return result;
}
跨域请求
跨域请求在后端配置即可
可以全局放行,也可以只针对某些地址允许
- 全局允许跨域请求
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(false);
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addExposedHeader("*");
UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
configurationSource.registerCorsConfiguration("/**",corsConfiguration);
return new CorsFilter(configurationSource);
}
}