1、yml配置
下面的服务器根据自己所用的进行调整即可
upload: file: # 这是linux服务器的上传路径 # location: file:/mnt/www/pp/test_ai/image #这是windows服务器的上传路径 location: file:d://image/ #这是访问的虚拟路径 path: /temp-image/** fileServer: #这是访问图片的服务 url: http://localhost:9099/test_api
2、上传controller
此方法中ObjectResponse是本人自定义的返回类,大家可以根据自己的来进行编写。
@RequestMapping({"/file"}) @RestController @CrossOrigin(origins = {"*"}, maxAge = 3600) /* loaded from: CarouseImageController.class */ public class FileUploadController { @Value("${upload.file.location}") private String fileLocation; @Value("${upload.file.path}") private String filePath; @Value("${fileServer.url}") private String fileServer; @PostMapping({"/importPicture"}) @ResponseBody @CrossOrigin(origins = {"*"}) public ObjectResponse importPicture(@RequestParam("file") MultipartFile file) throws FileNotFoundException { String filename = UUID.randomUUID() + ((String) Objects.requireNonNull(file.getOriginalFilename())).substring(file.getOriginalFilename().lastIndexOf(".")); File filepath = new File(this.fileLocation.replaceAll("file:", "") + filename); String.valueOf(filepath); try { file.transferTo(filepath); System.out.println("文件已存储成功,路径:" + filepath.getPath()); } catch (IOException e) { e.printStackTrace(); } return new ObjectResponse (Boolean.TRUE.booleanValue(), "操作成功!", (this.filePath + filename).replaceAll("\\*", "")); }
}
3、添加配置类(此类必须要有,不然是访问不了的)
@Configuration public class ProjectWebMvcConfigurer implements WebMvcConfigurer { @Value("${upload.file.location}") private String fileLocation; @Value("${upload.file.path}") private String filePath; @Bean TokenInterceptor paramInterceptor() { return new TokenInterceptor(); } public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler(new String[]{"/static/**"}).addResourceLocations(new String[]{"classpath:/static/"}); registry.addResourceHandler(new String[]{"/templates/**"}).addResourceLocations(new String[]{"classpath:/templates/"}); registry.addResourceHandler(new String[]{this.filePath}).addResourceLocations(new String[]{this.fileLocation}); } public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(paramInterceptor()).addPathPatterns(new String[]{"/**"}).excludePathPatterns(new String[]{"/static/**"}); } public void addCorsMappings(CorsRegistry registry) { System.out.println("----------------------"); registry.addMapping("/**").allowedOrigins(new String[]{"*"}).allowCredentials(true).allowedMethods(new String[]{AdminCommonConstant.RESOURCE_REQUEST_METHOD_GET, AdminCommonConstant.RESOURCE_REQUEST_METHOD_POST, AdminCommonConstant.RESOURCE_REQUEST_METHOD_DELETE, AdminCommonConstant.RESOURCE_REQUEST_METHOD_PUT, "OPTIONS"}).maxAge(3600L); } }