spring boot 接收前端上传的图片
spring boot 接收前端上传的图片,并储存到本地磁盘中,其实我不想存本地磁盘中,感觉很难移植,但是没找到其他方法。
参考文章:第一个文章链接,第二个文章链接
Controller里的代码:
@RestController
@RequestMapping("/api")
public class UploadDownHandler {
/**上传地址*/
@Value("${file.upload.path}")
private String path;
/**图片url前缀*/
@Value("${com.test.base_picture_url}")
private String base_picture_url;
/**
* 上传图片
* @param file
* @param request
* @return
* @throws IOException
*/
@ResponseBody
@PostMapping("/uploadPicture")
public JsonResult<Map> uploadPicture(@RequestParam("file")MultipartFile file, HttpServletRequest request) throws IOException{
//String base_picture_url = "http://localhost:8080/image/";
//获取文件在服务器的储存位置
File filePath = new File(path);
System.out.println("文件的保存路径"+path);
if(!filePath.exists() && !filePath.isDirectory()){
System.out.println("目录不存在,创建目录" + filePath);
filePath.mkdir();
}
//获取原始文件名称(包括格式)
String originalFileName = file.getOriginalFilename();
System.out.println("原始文件名称" + originalFileName);
//获取文件类型,以最后一个‘.’为标识
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
System.out.println("文件类型" + type);
//获取文件名称(不包含格式)
String name = originalFileName.substring(0,originalFileName.lastIndexOf("."));
//设置文件新名称:当前事件+文件名称(不包含格式)
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String date = sdf.format(d);
String fileName = date + name + "." +type;
System.out.println("新文件名称" +fileName);
//在指定路径下创建文件
File targetFile = new File(path,fileName);
Map<String,Object> result = new HashMap<String,Object>();//定义结果
//将文件保存到服务器指定位置
try{
file.transferTo(targetFile);
System.out.println("上传成功");
}catch (IOException e){
System.out.println("上传失败");
result.put("code",400);
e.printStackTrace();
return new JsonResult<>(result);
}
result.put("code",200);
result.put("picture",base_picture_url+ fileName);
System.out.println(result);
return new JsonResult<>(result);
}
}
配置映射路径:
@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
/**上传地址*/
@Value("${file.upload.path}")
private String filePath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/image/**").addResourceLocations("file:/" + filePath);
}
}
在配置文件中增加路径:
在 application.properties中
file.upload.path=E://img/
com.test.base_picture_url=http://localhost:8080/image/
我把localhost换成自己电脑的ip地址了
这样前端就获取到了图片的url地址。http://10.2.22.10:8080/image/cat.jpg 形如这样