java后台简单从阿里云上传下载文件并通知前端以附件的形式保存

2023-02-17,,,,

一、 首先开通阿里的OSS 服务 创建一个存储空间在新建一个Bucket 在你新建的bucket有所需的id和key

获取外网访问地址或者是内网 看个人需求 我使用的是外网(内网没用过 估计是部署到阿里云服务器可以使用内网) 获取endpoint

好了前期准备工作完事

以下是我项目的机构

pom 配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.</modelVersion> <groupId>xudy.top</groupId>
<artifactId>OssAction</artifactId>
<version>1.0-SNAPSHOT</version> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/>
</parent> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.7.</version>
</dependency> </dependencies> </project>

ConfigUtols 配置代码

@Component
public class ConfigUtils { /**
* 腾讯云配置
* @return
*/
@Bean
public OSSClient getCOSClient() {
return this.getOSSClient();
} /**
* 阿里云OSS对象存储 客户端
* @return
*/
public static OSSClient getOSSClient() {
String endpoint = "http://os.com";
String accessKeyId = "LTadAI";
String accessKeySecret = "zLIRj001";
// 创建OSSClient实例
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
return ossClient;
} }

Controller  里包含 上传 和下载代码:


@RestController
public class MainController { @Autowired
OSSClient ossClient; @GetMapping(value = "/upload")
public String OSSUpLoad(){ // 上传byte数组
// byte[] content = "Hello OSS xudy".getBytes();
// ossClient.putObject("xudy", "xudy", new ByteArrayInputStream(content)); String filePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + "top.jpg";
// 上传文件流
try {
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file); // 上传文件
ossClient.putObject("xudy", "txt.jpg", inputStream);
} catch (Exception e) {
// e.printStackTrace();
System.out.println("上传阿里云OSS服务器异常." + e.getMessage()); }
// 关闭client 正常开发的时候 做好把下面代码屏蔽
// ossClient.shutdown(); return "upload";
} @GetMapping(value = "/download")
public void OssAction(HttpServletRequest request, HttpServletResponse response){
try {
String fileName="txt.jpg";
String ossKey="txt.jpg";
// 从阿里云进行下载
OSSObject ossObject = ossClient.getObject("xudy",ossKey);//bucketName需要自己设置
// 已缓冲的方式从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent())); InputStream inputStream = ossObject.getObjectContent(); //缓冲文件输出流
BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
//通知浏览器以附件形式下载
// response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
// 为防止 文件名出现乱码
response.setContentType("application/doc");
final String userAgent = request.getHeader("USER-AGENT");
if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
fileName = URLEncoder.encode(fileName,"UTF-8");
}else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
fileName = new String(fileName.getBytes(), "ISO8859-1");
}else{
fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
}
response.addHeader("Content-Disposition", "attachment;filename=" +fileName);//这里设置一下让浏览器弹出下载提示框,而不是直接在浏览器中打开

            // 进行解码 如果上传时为了防止乱码 进行解码使用此方法
BASE64Decoder base64Decoder = new BASE64Decoder();
// byte[] car;
// while (true) {
// String line = reader.readLine();
// if (line == null) break;
// car = base64Decoder.decodeBuffer(line);
//
// outputStream.write(car);
// }
// reader.close(); byte[] car = new byte[1024];
int L; while((L = inputStream.read(car)) != -1){
if (car.length!=0){
outputStream.write(car, 0,L);
}
} if(outputStream!=null){
outputStream.flush();
outputStream.close();
} } catch (IOException e) {
e.printStackTrace(); } catch (OSSException e){ }
} /**
* 删除存储空间buckName
*/
public void deleteBucket(){
ossClient.deleteBucket(""); }
 

注意:在实际使用该方法下载的过程中,可能遇到服务器不报错,但就是下载不下来文件的问题,这样有可能是前端页面发出下载请求的方式有误,不能使用AJAX的get方式访问该方法,因为Ajax能够返回的数据格式只能为html,script,json,xml,不接受流的形式。笔者使用的方式是用window.location.href访问,或者使用from表单提交方式(GET/POST)。

源码:git@gitee.com:xdymemory00/OssDownLoad.git

借鉴来源:https://www.alibabacloud.com/help/zh/doc-detail/32014.htm

java后台简单从阿里云上传下载文件并通知前端以附件的形式保存的相关教程结束。

《java后台简单从阿里云上传下载文件并通知前端以附件的形式保存.doc》

下载本文的Word格式文档,以方便收藏与打印。