前端
<el-upload
class="upload-demo"
drag
action="http://localhost:8080/goods/upload"
name="image"
:on-success="upload"
multiple>
<i class="el-icon-upload"></i>
<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<div class="el-upload__tip" slot="tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
:on-success="upload"是上传成功的钩子,详细看elementui文档
后端
controller
@PostMapping("upload")
public Result uploadImg(@RequestParam("image") MultipartFile multipartFile) throws FileNotFoundException {
if (multipartFile.isEmpty()) {
//文件为空逻辑
}
String contentType = multipartFile.getContentType();
if (!contentType.contains("")) {
/
}
String root_fileName = multipartFile.getOriginalFilename();
//获取路径
//
String filePath ="src/main/resources/static/goods_ima";;
String file_name = null;
try {
file_name = ImageUtil.saveImg(multipartFile, filePath);
System.out.println("文件名:" + file_name);
} catch (IOException e) {
e.printStackTrace();
}
//封装Result
Map<String, Object> result = new HashMap<>();
result.put("imageUrl","http://localhost:8080/goods_ima/"+file_name);
return Result.ok().data(result);
}
上传文件的配置类
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
/**
* 在配置文件中配置的文件保存路径
*/
@Bean
public MultipartConfigElement multipartConfigElement(){
MultipartConfigFactory factory = new MultipartConfigFactory();
//文件最大KB,MB
factory.setMaxFileSize(DataSize.ofMegabytes(2));
//设置总上传数据总大小
factory.setMaxRequestSize(DataSize.ofMegabytes(20));
return factory.createMultipartConfig();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("配置文件已经生效");
//关于图片上传后需要重启服务器才能刷新图片
//这是一种保护机制,为了防止绝对路径被看出来,目录结构暴露
//解决方法:将虚拟路径/images/
// 向绝对路径 (D:\单子\仓库管理系统\后端\src\main\resources\static\goods_ima\)映射
String path="D:\\单子\\仓库管理系统\\后端\\src\\main\\resources\\static\\goods_ima\\";
registry.addResourceHandler("/goods_ima/**").addResourceLocations("file:"+path);
}
}
保存文件的逻辑
public class ImageUtil {
/**
* 保存文件,直接以multipartFile形式
* @param multipartFile
* @param path 文件保存绝对路径
* @return 返回文件名
* @throws IOException
*/
public static String saveImg(MultipartFile multipartFile, String path) throws IOException {
File file = new File(path);
if (!file.exists()) {
file.mkdirs();
}
FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
String fileName = System.currentTimeMillis() + ".png";
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
byte[] bs = new byte[1024];
int len;
while ((len = fileInputStream.read(bs)) != -1) {
bos.write(bs, 0, len);
}
bos.flush();
bos.close();
return fileName;
}
}
效果
前端上传
保存在后端的文件