使用springboot 图片上传和显示

一、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标签测试一下。
在这里插入图片描述

以上就是图片上传以及浏览器上显示的过程~

  • 8
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值