阿里OSS上传下载

最近工作中,遇到了一个业务,需要将本地的excel上传到阿里云作为模板,下载模板的时候从阿里云上下载要求用流的形式。总结一下,希望能帮到别人。

上传:

 @PostMapping("import")
    public Result userImpoetTemplate(@RequestBody MultipartFile multipartFile) {
        File resultFile = new File("选择一个和文件类型相同的文件绝对路径");
        try {
            String fileName = "filename";
     //将MultipartFile类型 转为File
            multipartFile.transferTo(resultFile);
            if (resultFile != null) {
//封装了oss的上传方法,可以参考阿里云sdk
                String url = fileUploadSerivice.uploadByPart(fileName + ".xlsx", resultFile);
                url = url.replaceFirst("http://", "https://");
                System.out.println(url);
            } else {
                throw new ServiceException("生成文件失败");
            }

        } catch (Exception e) {

            throw new ServiceException("文件生成失败");
        } finally {
            if (resultFile.exists()) {
                resultFile.delete();
            }
        }
        return new Result();
    }

下载:

 @RequestMapping(value = "down", method = RequestMethod.POST)
    public Result downUserTemplate(HttpServletResponse response) {
        String filename = "filename.xlsx";
        try {
            filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
            response.reset();
//xslx格式必须是这个
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            response.setHeader("Content-Disposition", String.format("attachment;filename=%s", URLEncoder.encode(filename, "utf-8")));
            InputStream inputStream = fileUploadSerivice.downloadFile(filename);
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result();
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值