因为要从oss下载、查看、上传工具类,所以对这几个方法做了一个封装,已经经过测试,可以直接使用

1、yml添加上阿里云配置、添加maven配置

注意这里的objectName: xxx/xxx/,前面没有反斜杠/

oss:region: xxxaccessKeyId: xxxxxaccessKeySecret: xxxxxbucket: xxxxxobjectName: xxx/xxx/
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version>
</dependency>

2、工具类代码

package com.fj.utils;import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.sun.deploy.net.URLEncoder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletResponse;
import java.io.*;/*** oss文件查看,上传,下载工具类** @author: honry.guan* @date: 2021/2/20 16:45*/
@Data
@Component
public class OssClientUtl {@Value(value = "${oss.region}")private String region;@Value(value = "${oss.accessKeyId}")private String accessKeyId;@Value(value = "${oss.accessKeySecret}")private String accessKeySecret;@Value(value = "${oss.bucket}")private String bucketName;@Value(value = "${oss.objectName}")private String objectName;/*** 通过文件名字读取文件内容** @param fileName 文件名:postman.txt* @return 文件内容字符串*/public String seeByFileName(String fileName) {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);OSSObject ossObject = ossClient.getObject(bucketName, objectName + fileName);BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));StringBuilder sb = new StringBuilder();try {while (true) {String line = reader.readLine();if (line == null) {break;}sb.append(line).append("\n");}reader.close();} catch (IOException e) {e.printStackTrace();}// 关闭OSSClient。ossClient.shutdown();return sb.toString();}/*** 读取文件内容** @param objectName oss完整的key,例子:fj_wechat_web/public/postman.txt* @return 文件内容字符串*/public String seeByObjectName(String objectName) {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);OSSObject ossObject = ossClient.getObject(bucketName, objectName);BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));StringBuilder sb = new StringBuilder();try {while (true) {String line = reader.readLine();if (line == null) {break;}sb.append(line).append("\n");}reader.close();} catch (IOException e) {e.printStackTrace();}// 关闭OSSClient。ossClient.shutdown();return sb.toString();}/*** 读取文件内容** @param url 能直接访问的url* @return 文件名*/public String seeByUrl(String url) {return seeByFileName(getFileNameByUrl(url));}/*** 绝对路径上传文件** @param filePath 绝对路径:D:\postman.txt*/public void upload(String filePath) {try {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);InputStream inputStream = new FileInputStream(filePath);ossClient.putObject(bucketName, objectName + filePath, inputStream);ossClient.shutdown();ossClient.shutdown();} catch (FileNotFoundException e) {e.printStackTrace();}}/*** 网页上传文件** @param file MultipartFile网页上传文件*/public void uploadMultipartFile(MultipartFile file) {try {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);ossClient.putObject(bucketName, objectName + file.getOriginalFilename(), file.getInputStream());ossClient.shutdown();ossClient.shutdown();} catch (IOException e) {e.printStackTrace();}}/*** 通过文件名字下载** @param response response* @param fileName 文件名字,带后缀,例子:postman.txt*/public void downloadByFileName(HttpServletResponse response, String fileName) {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);OSSObject ossObject = ossClient.getObject(bucketName, objectName + fileName);BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());try {BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());//通知浏览器以附件形式下载response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));byte[] car = new byte[1024];int len = 0;while ((len = in.read(car)) != -1) {out.write(car, 0, len);}out.flush();out.close();in.close();ossClient.shutdown();} catch (IOException e) {e.printStackTrace();}}/*** 通过oss的完整key下载** @param response   response* @param objectName oss完整的key,例子:fj_wechat_web/public/postman.txt*/public void downloadByObjectName(HttpServletResponse response, String objectName) {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);OSSObject ossObject = ossClient.getObject(bucketName, objectName);BufferedInputStream in = new BufferedInputStream(ossObject.getObjectContent());try {BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());//通知浏览器以附件形式下载response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("postman.txt", "utf-8"));byte[] car = new byte[1024];int len;while ((len = in.read(car)) != -1) {out.write(car, 0, len);}out.flush();out.close();in.close();ossClient.shutdown();} catch (IOException e) {e.printStackTrace();}}/*** 通过oss的完整key下载** @param response   response* @param url 能直接访问的url地址*/public void downloadByUrl(HttpServletResponse response, String url) {downloadByFileName(response,getFileNameByUrl(url));}/*** 判断文件是否存在** @param fileName 文件名:postman.txt* @return true文件存在,false文件不存在*/public boolean isExitByFileName(String fileName) {String endpoint = "http://" + region + ".aliyuncs.com";OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);return ossClient.doesObjectExist(bucketName, objectName + fileName);}/*** 判断文件是否存在** @param url 能直接访问的完整url* @return true文件存在,false文件不存在*/public boolean isExitByUrl(String url) {return isExitByFileName(getFileNameByUrl(url));}/*** 通过url获取文件名* @param url 能够直接访问的url* @return 文件名:postman.txt*/public String getFileNameByUrl(String url){String[] split = url.split("/");return split[split.length-1];}
}

3、测试

@RestController
@RequestMapping("/test")
public class TestController {@Autowiredprivate OssClientUtl ossClientUtl;@GetMapping("/see")public BaseResult see() {return BaseResult.ok(ossClientUtl.seeByFileName("postman.txt"));}@GetMapping("/upload")public BaseResult upload(@RequestParam("file") MultipartFile file) {ossClientUtl.uploadMultipartFile(file);return BaseResult.ok("上传成功");}@GetMapping("/download")public void download(HttpServletResponse response) {String fileName = "postman.txt";ossClientUtl.downloadByFileName(response, fileName);}
}

java的springboot项目操作阿里云OSS下载文件、查看文件内容、上传文件,自定义工具类相关推荐

  1. 使用PicGo+阿里云OSS实现md文档图片上传

    使用PicGo+阿里云OSS实现md文档图片上传 这次给大家带来的是PicG0+阿里云Oss+typora的图床环境搭建,帮助大家提高工作效率+写博客速度! 1.typora安装 给大家一个链接:ty ...

  2. springboot项目整合阿里云oss的内容审核

    springboot项目整合阿里云 内容审核 第一 添加依赖 <dependency><groupId>com.aliyun</groupId><artifa ...

  3. 阿里云使用idea通过hdfs api来上传文件时出现could only be written to 0 of the 1 minReplication nodes.错误

    问题描述: 使用阿里云服务器,在本地windows电脑上使用idea进行hdfs api操作来上传文件时出现错误如下: org.apache.hadoop.ipc.RemoteException(ja ...

  4. Python使用阿里云对象存储OSS--服务器端上传文件

    一直在使用阿里云对象存储Oss,今天来总结一下基本用法,主要写个逻辑,具体操作都有详细的文档,会附链接 1  开通服务 首先需要开通oss服务以及创建存储空间,需要注意的是开通完oss服务之后默认的是 ...

  5. 阿里云轻量应用服务器 怎么控制怎么上传文件怎么安装JDK和Tomcat怎么完成JavaWeb的部署...

    你是否遇到过这些问题,自己的javaweb项目本地运行一切正常,但是一旦转移到阿里服务器之类的.就出现以下问题. 1 jsp无法解析java类 2 Only a type can be importe ...

  6. 一文读懂什么是阿里云OSS,如何使用Java操作阿里云OSS?

    一.什么是阿里云OSS OSS: Object Storage Service 对象存储服务是一种海量.安全.低成本.高可靠的云存储服务,适合存放任意类型的文件.容量和处理能力弹性扩展,多种存储类型供 ...

  7. 利用Jenkins自动化部署springboot项目到阿里云服务器(centos8)

    背景: 最近想部署一个springboot项目到阿里云服务器里面.捣鼓了很久,构建了很多次,都失败了!实在是一脸辛酸,有点气馁~ 在此想记录一下构建的过程. 不了解Jenkins之前,觉得Jenkin ...

  8. Golang操作阿里云OSS上传文件

    为什么要使用OSS?应用场景是什么? 最近在开发考试系统,里面需要上传课件,课件包括pdf,map等等各种类型的文件,这些文件不能像图片一样,直接上传到项目目录下面,需要单独存放,阿里云就提供了存储方 ...

  9. 小程序配置阿里云OSS下载文件,在请求头里配置生成强制下载链接,(拿到下载链接可以下载文件至本地)

    小程序配置阿里云OSS下载文件,在请求头里配置生成强制下载链接,(拿到下载链接可以下载文件至本地)(Win10电脑开发环境)**这里只说明小程序端问题**<菜鸡总结大神勿喷!蟹蟹~> 大体 ...

最新文章

  1. QML基础类型之variant
  2. PAT1021 Deepest Root
  3. Java同步组件之CyclicBarrier,ReentrantLock
  4. apache编译出错 error: mod_deflate has been requested
  5. CentOS+Asterisk+Freepbx
  6. Lwip协议详解(基于Lwip 2.1.0)-IP协议
  7. Ubuntu 环境下SVN添加新项目
  8. 图书管理系统数据库SQL设计思路
  9. ubuntu 深度音乐播放器
  10. 互联网公司大数据,主要有什么优势和劣势?
  11. [导入]polygraph3d三维运行时引擎为silverlight 1.0.zip(15.69 KB)
  12. 华为云sql工程师评测答题[青铜+白银]
  13. project.json
  14. 前端原生下载excel表格
  15. 如何在QEMU上执行iOS并启动一个交互式bash shell,内含整个安装流程并且提供了相关工具(二)
  16. 选择WMS仓库管理系统之前,企业应该准备些什么
  17. ERROR: Timeout after 10 minutes ERROR: Error fetching remote repo 'origin'
  18. linux inotifywait脚本,inotify之inotifywait命令详解
  19. 【无标题】threejs 使用composer后的场景变暗解决
  20. 居家办公必备的5款功能强大且免费的软件

热门文章

  1. 图书销售系统(C#界面设计)
  2. glut库更新旧程序无法完成编译问题描述
  3. 结束计算机进程的快捷键,结束进程快捷键是什么?Win7结束进程快捷键介绍
  4. 英语科技论文撰写技巧
  5. JAVA 操作excel的问题,待高手解决。。。
  6. Win7桌面怎么显示我的电脑图标
  7. linux 下网络编程 聊天室项目
  8. 嵌入式linux入门学习规划
  9. 华为OD机试 - 分班问题
  10. 【Altium designer】新手入门(PCB layout设计)