yml配置:
upload:
url: D:\jar\
localhost: http://127.0.0.1:9001/upload/
@Configuration
public class UploadConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 映射名
registry.addResourceHandler("/upload/**")
// 映射路径
.addResourceLocations("file:D:/jar/");
}
}
@Value("${upload.url}")
private String pathUrl;
@Value("${upload.localhost}")
private String location;
/**
* 上传图片
*
* @param file
* @return
*/
@PostMapping(value = "/uploadImage")
@ResponseBody
public String insertOrderImg(@RequestParam("file") MultipartFile file) {
String originalFilename = file.getOriginalFilename();
String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//设置允许上传文件类型
String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
String imgUrl = null;
// 判断是否包含
if (suffixList.contains(extName.trim().toLowerCase())) {
// 保存文件的路径
String path = pathUrl + originalFilename;
// spring的transferTo保存文件方法
try {
file.transferTo(new File(path));
imgUrl = location + originalFilename;
} catch (IOException e) {
e.printStackTrace();
return "上传图片失败";
}
}
return imgUrl;
}
在浏览器上输入网络地址访问
图片保存路径