使用springboot实现一个最简单版本的上传文件接口
java
private String uploadPath = "C:/imageFiles";
@RequestMapping(value = "/upload", method = RequestMethod.POST)
private Result upload( @RequestParam("modelName") String modelName,
@RequestParam("file") MultipartFile multipartFile) {
try {
StrBuilder sb = new StrBuilder();
sb = sb.append(uploadPath).append(modelName);
FileUtil.mkdir(sb.toString());
String newFileName = System.currentTimeMillis() + multipartFile.getOriginalFilename();
sb = sb.append("/").append(newFileName);
FileOutputStream fileOutputStream = new FileOutputStream(sb.toString());
fileOutputStream.write(multipartFile.getBytes());
fileOutputStream.close();
return new Result().success("/" + modelName + "/" + newFileName);
} catch (IOException e) {
e.printStackTrace();
log.info("上传文件IO异常");
return new Result().error("上传文件IO异常");
}
}
上传完成之后需要访问,可以使用springmvc静态资源代理(线上项目不推荐,建议使用nginx静态资源代理)
java
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 本地资源映射
registry.addResourceHandler("/images/**").addResourceLocations("file:" + "C:/imageFiles/");
}
}
尝试请求一下
成功返回!