SpringBoot访问图片/文件

1、SpringMvc静态资源访问

需要所有图片在同一文件夹下,通过文件名直接访问

spring.mvc.static-path-pattern=pic/**

spring.resources.static-locations=file:/opt/project/epin/images

2、ResponseEntity返回二进制流

后端:


//读取文件流
    @Override
    public ResponseEntity<byte[]> readFile(String filePath, String path) throws IOException {
        InputStream fileInputStream = null;
        byte[] bytes = null;
        HttpHeaders headers = null;
        try {
            String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
            File file = new File(filePath);
            if(!filePath.endsWith(".zip")){
                fileInputStream = new FileInputStream(file);
            }else{
                //若是压缩文件
                // new ZipFile(zipFilePath,);
//                java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file,Charset.forName("GBK"));
//                fileInputStream = ZipToTreeUtil.getZipFileInputStree(zipFile,path);
//                fileName = path.substring(path.lastIndexOf("/")+1);
                return null;
            }

            headers = new HttpHeaders();
            fileName = URLEncoder.encode(fileName, "GBK");
            if(filePath.endsWith(".jpg")||filePath.endsWith(".jpeg")) headers.setContentType(MediaType.IMAGE_JPEG);
            else if(filePath.endsWith(".png")) headers.setContentType(MediaType.IMAGE_PNG);
            else if(filePath.endsWith(".gif")) headers.setContentType(MediaType.IMAGE_GIF);
            else {
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.add("Content-Disposition", "attachment;filename=\""+ fileName + "\"");
            }
            bytes = IOUtils.toByteArray(fileInputStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fileInputStream!=null)
                fileInputStream.close();
        }

        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.OK);
    }

前端

            this.axios({
              url,
              method,
              params,
              responseType:"blob"
            })
            .then(response=>{
              console.log(response);
              this.img = window.URL.createObjectURL(response.data) ;
          })

踩坑:
后端设置返回类型image/jpeg(gif/png),前端设置返回类型blob,
转换成URL:window.URL.createObjectURL(response.data),一定要是data

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值