前言
今天在使用springboot写文件上传到服务器的功能的时候,在本地(windows系统)可以运行成功,但是将代码上传到服务器(Linux系统)的时候就会报这个错误,上传的文件不能写到服务器中,并且会在服务器上创建一个空的文件夹,现在记录一下自己的解决办法
解决办法
首先先在config文件夹中加入一个配置类
package com.homyit.kg.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class UploadFilePathConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:/usr/officialWebsite/static/upload/");
}
}
这里我重构了springboot的WebMvcConfigurer,用这种办法可以自定义文件写入的位置(.addResourceLocations(“file:/usr/officialWebsite/static/upload/”);),并给它创建一个虚拟的外部访问路径(registry.addResourceHandler("/upload/**"))
文件写入成功,大家也可以将这个写入位置设置为服务器中tomcat的webapps的文件目录下,与前端的image文件放在一起,这样可以方便前端对该资源的调用。
上传文件的工具类代码
下面的代码,只是部分代码,了解一下大概的逻辑就好。
public class ImageLoad {
public ImageInfo upLoadHurl(MultipartFile image, String filePath, int mid, String name) {
ImageInfo info = new ImageInfo();
String fileName;
info.setCode(200);
info.setMessage("success");
info.setData(new ArrayList<String>());
if (image != null) {
File dir = new File(filePath, name);
if (!dir.exists()) {
dir.mkdirs();
}
String extension = FilenameUtils.getExtension(image.getOriginalFilename());
// // 重新生成文件名
fileName = mid + "." + extension;
if (checkFormat("." + extension)) {
try {
// 写入文件
image.transferTo(new File(dir, fileName));
info.getData().add((dir + "\\" + fileName).replace("\\", "/"));
} catch (IOException e) {
info.setCode(500);
info.setMessage("操作失败");
}
}
} else {
info.setCode(500);
info.setMessage("图片不存在");
}
return info;
}
上传文件的代码的主要代码
public RestfulInfo updateH_url(MultipartFile image) throws FileNotFoundException {
RestfulInfo info = new RestfulInfo();
try{
ImageLoad imageLoad = new ImageLoad();
String filePath = ResourceUtils.getURL("file:/usr/officialWebsite/static/upload/").getPath() + "public/members/h_url/";
String h_url = serverMembersMapper.selectAdH_urlByAdId(admin_id);
new File(h_url).delete();
ImageInfo imageInfo = imageLoad.upLoadHurl(image, filePath, 1, "1");
if (imageInfo.getCode() == 200) {
Amapper.updateAdH_urlByAdId(imageInfo.getData().get(0), admin_id);
info.setCode(200);
info.setMessage("success");
}
}catch (Exception e){
info.setCode(500);
info.setMessage("未知错误");
}
return info;
}