1.yml配置
file:
upload-path: F:/path/to/upload/directory/
upload-url: /upload/
2.上传Controller
import com.books.mode.result.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
@RequestMapping("/upload/upload")
@RestController
public class UploadController {
@Value("${file.upload-path}")
private String uploadPath;
@Value("${file.upload-url}")
private String uploadUrl;
@PostMapping("/file")
public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
try {
if (file.isEmpty()) {
return new AjaxResult(400, "文件为空", false);
}
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
String yearPath = yearFormat.format(new Date());
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String monthPath = monthFormat.format(new Date());
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String dayPath = dayFormat.format(new Date());
String folderPath = yearPath + "/" + monthPath + "/" + dayPath;
File directory = new File(uploadPath + folderPath);
if (!directory.exists()) {
directory.mkdirs();
}
String orgName = file.getOriginalFilename();
String suffixName = orgName.substring(orgName.lastIndexOf("."));
String fileName;
if (orgName.contains(".")) {
fileName = "测试图片_" + System.currentTimeMillis() + suffixName;
} else {
return new AjaxResult(400, "不是文件/图片/视频", false);
}
Path destination = Paths.get(uploadPath, folderPath, fileName);
Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING); // 保存文件
String fileUrl = "http://192.168.176.13:9090" + uploadUrl + folderPath + "/" + fileName;
return new AjaxResult(200, "上传成功", fileUrl, true);
} catch (Exception e) {
e.printStackTrace();
}
return new AjaxResult(500, "内部异常", false);
}
}
3.配置WebMvcConfig:配置资源映射路径和访问路径
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 WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**")
.addResourceLocations("file:F:/path/to/upload/directory/");
}
}
4.测试上传:使用Apifox或者Postman,可获取URL(data),供前端页面使用
5.浏览器上拼接完整地址预览图片