一、application.properties配置文件
###文件上传 springboot版本2.0.4
#是否启用文件上传功能
spring.servlet.multipart.enabled=true
#指定文件写入磁盘后的阈值,默认为0
spring.servlet.multipart.file-size-threshold=0
#指定文件的位置, 没有指定时会自动创建一个临时文件夹
spring.servlet.multipart.location=D:/springboot/upload
#指定上传文件大小, 默认1M
spring.servlet.multipart.max-file-size=50Mb
#指定multipart / form-data请求允许的最大大小, 默认10M
spring.servlet.multipart.max-request-size=100Mb
#是否在文件或参数访问时懒惰地解析多部分请求
spring.servlet.multipart.resolve-lazily=false
#图片上传路径映射 自定义属性
upload.picture.path=D:/springboot/upload/
二、控制层
@Controller
public class PhotoController extends BaseController {
@Value("${upload.picture.path}")
private String uploadPicturePath;
@javax.annotation.Resource
private ResourceLoader resourceLoader;
/**
* @Description //上传
* @Param [multipartFile]
* @Author oneTi
* @Date 15:10 2018/8/17
* @Return java.lang.String
**/
@RequestMapping("/photo/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile multipartFile){
try{
//multipartFile.getOriginalFilename() 获取文件原始名称
//new File(multipartFile.getOriginalFilename()) 根据获取到的原始文件名创建目标文件
//multipartFile.transferTo() 将收到的文件传输到目标文件中
multipartFile.transferTo(new File(multipartFile.getOriginalFilename()));
}
catch (IOException e){
e.printStackTrace();
}
return "false";
}
/**
* @Description //显示
* @Param [fileName]
* @Author oneTi
* @Date 15:11 2018/8/17
* @Return org.springframework.http.ResponseEntity<org.springframework.core.io.Resource>
**/
@RequestMapping("/{fileName:.+}")
@ResponseBody
public ResponseEntity<Resource> show(@PathVariable String fileName){
try
{
//resourceLoader.getResource("file:" + uploadPicturePath + fileName) 返回指定路径的资源句柄,这里返回的就是URL [file:D:/springboot/upload/test.png]
//ResponseEntity.ok(T) 返回指定内容主体
return ResponseEntity.ok(resourceLoader.getResource("file:" + uploadPicturePath + fileName));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
}
三、前端页面
<!--图片上传表单-->
<form action="/photo/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="">
<input type="submit" value="submit">
</form>
<!--图片显示-->
<img src="/test.png" alt="">
就用简单的img标签测试一下。
以上就是图片上传以及浏览器上显示的过程~