application.yml 文件添加配置: file-save-path: D:/uploadFile/ host: 'http://192.168.110.186:8990'
添加配置文件:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${file-save-path}")
private String fileSavePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
/**
* 配置资源映射
* 意思是:如果访问的资源路径是以“/uploadFile/”开头的,
* 就给我映射到本机的“D:/uploadFile/”这个文件夹内,去找你要的资源
* 注意:D:/uploadFile/ 后面的 “/”一定要带上
*/
registry.addResourceHandler("/uploadFile/**")
.addResourceLocations("file:"+fileSavePath);
}
}
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
public class UploadUtils {
/**
* 单文件上传工具类
* @param fileSavePath
* @param file
* @return
*/
public static String uploadFile(String fileSavePath, MultipartFile file){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
String format = sdf.format(new Date());
File folder = new File(fileSavePath + format);
String filePath="";
if (!folder.isDirectory()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() +
oldName.substring(oldName.lastIndexOf("."), oldName.length());
try {
file.transferTo(new File(folder, newName));
filePath = "/uploadFile/" + format + newName;
} catch (IOException e) {
e.printStackTrace();
return "error";
}
return filePath;
}
/**
* 文件删除工具类
* @param filePath
* @return
*/
public static void delFile( String filePath){
File deleteFile = new File(filePath);
if (deleteFile.exists()){
deleteFile.delete();
}
}
}
@Value("${host}")
private String host;
@Value("${file-save-path}")
private String fileSavePath;
/**
* 信息发布附属文件上传接口
* @param file
* @return
*/
@RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
public ResultVo uploadFile(MultipartFile file){
if(file != null){
//上传文件
String result = UploadUtils.uploadFile(fileSavePath, file);
if( "error".equals(result)){
return ResultBuilderVo.error(result);
}
//写入文件路径: http://localhost:8080/uploadFile/2023/12/27/807f116b-eaa1-42e9-adf4-bdd21bbfb530.png
return ResultBuilderVo.success(host + result);
}else {
return ResultBuilderVo.error("请上传图片!");
}
}