图片上传代码 controller
/**
* @description 文件上传 (包括了用户和员工) 测试已通过
* @param response
* @return void
* @throws
* @author 梁XL
* @date 2020/1/7
*/
@PostMapping("/upload")
public void insertOrderImg(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
// 返回Map
Map<String, Object> resultMap = new HashMap<>();
// 文件上传路径
String location = "D:\\photos\\"; //TODO 改为服务器路径
if (!file.isEmpty()) {
// 获取文件原始名称 a.png -> a
String originalFilename = file.getOriginalFilename();
// 获取文件后缀 .png
String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
//设置允许上传文件类型
String suffixList = ".jpg,.png,.ico,.bmp,.jpeg";
// 判断是否包含
if (suffixList.contains(extName.trim().toLowerCase())) {
// 保存文件的路径
String fileName = UUID.randomUUID() + extName;
String path = location + fileName;
// 查看路径是否存在,不存在就创建
//image/jpeg
if (!new File(path).exists()) {
boolean mkdirs = new File(path).mkdirs();
}
// spring的transferTo保存文件方法
try {
file.transferTo(new File(path));
String imgUrl = Config.host + fileName;
resultMap.put("code", "200");
resultMap.put("msg", "图片上传 success!");
resultMap.put("data", imgUrl);
} catch (IOException e) {
e.printStackTrace();
log.error("上传文件出错!");
resultMap.put("code", "500");
resultMap.put("msg", "服务器错误!");
resultMap.put("data", "");
}
}
} else {
resultMap.put("code", "500");
resultMap.put("msg", "未选择图片!");
resultMap.put("data", "");
}
super.mapToJson(resultMap,response);
}
yml 配置文件大小限制
spring:
servlet:
multipart:
max-file-size: 5MB
max-request-size: 60MB
config 文件配置的 ip+ 端口
// 服务器IP:Port
public static String host = "http://192.168.31.28:8080/photos/";
本地图片映射成ip和端口
/**
* @author 梁XL
* @description
* @date 2020/1/11
*/
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//和页面有关的静态目录都放在项目的static目录下
// registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
//上传的图片在D盘下的OTA目录下,访问路径如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
//其中OTA表示访问的前缀。"file:D:/OTA/"是文件真实的存储路径
registry.addResourceHandler("/photos/**").addResourceLocations("file:D:/photos/");
}
}
使用postman测试
使用浏览器访问大功告成!
---------------------
作者:开发狗
来源:CSDN
原文:https://blog.csdn.net/Phone_1070333541/article/details/104011913
版权声明:本文为上一个作者原创文章,转载请附上博文链接请询问开发狗!