一、配置信息
file:
accessPath: /upfs/
staticAccessPath: /upfs/**
uploadFolder: D://temp/
二、配置上传参数
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;
@Configuration
@Data
public class FileUploadConfig implements WebMvcConfigurer {
@Value("${file.staticAccessPath}")
private String staticAccessPath;
@Value("${file.uploadFolder}")
private String uploadFolder;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath).addResourceLocations("file:" + uploadFolder);
}
}
三、controller部分
@RestController
@CrossOrigin
@RequestMapping("/file")
@SuppressWarnings("unchecked")
public class FileUploadController {
@Value("${file.uploadFolder}")
private String realBasePath;
@Value("${file.accessPath}")
private String accessPath;
@Resource
private Environment environment;
@PostMapping(value = "/upload")
@ResponseBody
@CrossOrigin(origins = "*", maxAge = 3600)
public List<String> fileUpload(@RequestParam("file") MultipartFile[] files, Integer fullUrl) {
List<String> result = new ArrayList<>();
if (files == null || files.length <= 0) {
return result;
}
for (int i = 0; i < files.length; i++) {
if (files[i].isEmpty()) {
return result;
}
}
try {
return uploadFile(files);
} catch (Exception e) {}
return result;
}
private List<String> uploadFile(MultipartFile[] files) {
List<String> result=new ArrayList<>();
String fileName="";
for (int i = 0; i < files.length; i++) {
fileName = files[i].getOriginalFilename();
try {
String url =saveFile(files[i]);
result.add(url);
} catch (Exception e) {}
return result;
}
}
return result;
}
private String saveFile(MultipartFile file) throws Exception{
String fileName = file.getOriginalFilename();
String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
InputStream inputStream = file.getInputStream();
String newFileName = UUID.randomUUID().toString() + "." + fileSuffix;
Date todayDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String today = dateFormat.format(todayDate);
String saveToPath = accessPath + today + "/";
String realPath = realBasePath + today + "/";
String filepath = realPath + newFileName;
File destFile = new File(filepath);
if (!destFile.getParentFile().exists()) {
Boolean b = destFile.getParentFile().mkdirs();
}
OutputStream outputStream = new FileOutputStream(destFile);
byte[] bs = new byte[1024];
int len = -1;
while ((len = inputStream.read(bs)) != -1) {
outputStream.write(bs, 0, len);
}
inputStream.close();
outputStream.close();
return saveToPath + newFileName;
}
}