java oss文件上传和下载工具类

本文介绍了一个基于阿里云OSS实现的文件上传、获取外链及下载功能的方法。通过提供的代码示例,展示了如何使用Java进行文件上传、生成文件外链及文件下载等操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


public List<String> uploadFile (@RequestPart(value = "file") MultipartFile[] file, @RequestParam(value = "pathKey") String pathKey) {
   List<String> urlArray = new ArrayList<String>();
   if (file.length > 0) {
      if (StringUtils.isEmpty(pathKey)) {
         throw new RestException("pathKey cannot be null");
      }
      for (MultipartFile multipartFile : file) {
         String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf(".") + 1);
         try {
            String tempUrl = aliyunOSSUtil.normalFileStreamUpload(multipartFile.getBytes(), pathKey, suffix);
            urlArray.add(tempUrl);
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

   } else {
      throw new RestException("上传文件不能为空");
   }
   return urlArray;
}

public String normalFileStreamUpload (byte[] data, String path) {
   // 创建OSSClient实例
   OSS ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
   try (ByteArrayInputStream input=new ByteArrayInputStream(data)) {
      //校验Bucket
      if (ossClient.doesBucketExist(bucketName)) {
     
      } else {
         ossClient.createBucket(bucketName);
      }
      ossClient.putObject(bucketName, path, input);
      return domain + "/" + path;
   }catch (OSSException e) {
      e.printStackTrace();
   } catch (ClientException e) {
      e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }finally {
      // 关闭OSSClient
      ossClient.shutdown();
   }

   return null;
}

获取文件的外链
public String getOuterUrl(String pathKey) {
   OSSClient ossClient = new OSSClient(domain, accessKeyId,accessKeySecret);
   // 设置URL过期时间为12小时
   Date expiration = new Date(new Date().getTime() + 12 * 3600 * 1000);
   GeneratePresignedUrlRequest generatePresignedUrlRequest ;
   generatePresignedUrlRequest =new GeneratePresignedUrlRequest(bucketName, pathKey);
   generatePresignedUrlRequest.setExpiration(expiration);
   URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
   return url.toString();
}

文件下载

public void fileDownload (String path, HttpServletResponse response) {
   String filePath = getOssKey(path);
   InputStream in = null;
   ServletOutputStream out = null;
   try {
      String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
      in = this.fileDownload(fileName);
      if (in==null){
         throw new RestException(ResultCode.FAILED.getCode(), ResultCode.FAILED.getMsg());
      }
      response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName.split("/")[2], "UTF-8"));
      out = response.getOutputStream();
      byte[] data = new byte[1024];
      boolean var8 = false;

      int len;
      while((len = in.read(data)) != -1) {
         out.write(data, 0, len);
      }

      out.flush();
   } catch (Exception e) {
      logger.info(Logger.EVENT_SUCCESS, "AliyunOSS fileDownload(String path, HttpServletResponse response) failed");
      e.printStackTrace();
   } finally {
      try {
         if (in != null) {
            in.close();
         }
         if (out != null) {
            out.close();
         }
      } catch (Exception var15) {
         var15.printStackTrace();
      }
   }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值