文件上传之MultipartFile使用
一、单/多文件上传使用例子:
工程路径如下
-src
|--main.java
--controller
--service
|--config
--ImageStorageProperties.java
--WebAppConfig.java
|--resource
|--config
--image-storage.properties
1.controller层
@CrossOrigin("*") @RequestMapping(value = "/putImages",method = RequestMethod.POST, headers = "Accept=application/json") public String putImages(@RequestBody MultipartFile[] files, HttpServletRequest request) { return putImgService.putImages(files,request);
}
2.service层
/** * 图片单/多张上传 * @param files 文件 * @return */ public String putImages(MultipartFile[] files, HttpServletRequest request) { String imgName = ""; if (files == null || files.length == 0) { return "图片为空"; } //遍历并保存文件 for (MultipartFile file : files) { // 图片传到服务器 imgName=imgUpload(file); if ("".equals(imgName)) { return "图片上传失败"; } } return "图片上传成功"; } /** * 图片传到服务器 * @param file * @return 图片路径 */ public String imgUpload(MultipartFile file) { String fileName = file.getOriginalFilename(); String suffixName = fileName.substring(fileName.lastIndexOf(".")); fileName = UUID.randomUUID() + suffixName; // 图片存储地址,例如"E:/imagesServer/" String parent = imageStorageProperties.getStoreUrl(); String imgName = ""; try { File targetFile = new File(parent, fileName); // 创建文件夹 if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } // 将上传文件存储到服务器中 file.transferTo(targetFile); // 背景图片地址 imgName = targetFile.getName(); // 图片显示地址,例如"http://localhost:8080/imgFiles/" + imgName imgName = imageStorageProperties.getHttpUrl() + imgName;
System.out.println(imgName); } catch (IOException e) { e.printStackTrace(); } return imgName; }
3.文件存储路径配置
1)image-storage.properties配置文件如下
image.httpUrl=http://localhost:8080/imgFiles/ image.storeUrl=E:/imagesServer/
2)ImageStorageProperties.java配置类如下
@ConfigurationProperties(prefix = "image", ignoreUnknownFields = false) @PropertySource(value = {"classpath:config/image-storage.properties"},encoding="utf-8") public class ImageStorageProperties { private String httpUrl; private String storeUrl; public String getHttpUrl() { return httpUrl; } public void setHttpUrl(String httpUrl) { this.httpUrl = httpUrl; } public String getStoreUrl() { return storeUrl; } public void setStoreUrl(String storeUrl) { this.storeUrl = storeUrl; } }
4.拦截器配置
WebAppConfig.java配置如下
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebAppConfig extends WebMvcConfigurerAdapter { @Autowired private ImageStorageProperties imageStorageProperties; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/imgFiles/**").addResourceLocations("file:"+imageStorageProperties.getStoreUrl()); super.addResourceHandlers(registry); } }