OSS文件下载的踩坑之路

过年过的在家带着无聊但是什么也不想干,哎,废了废了

今天做OSS文件下载的时候,怎么整都是乱码,整崩溃了。

官网给的例子也是有点狗(如下)

// Endpoint以杭州为例,其它Region请按实际情况填写。
String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
String accessKeyId = "<yourAccessKeyId>";
String accessKeySecret = "<yourAccessKeySecret>";
String bucketName = "<yourBucketName>";
String objectName = "<yourObjectName>";

// 创建OSSClient实例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

// ossObject包含文件所在的存储空间名称、文件名称、文件元信息以及一个输入流。
OSSObject ossObject = ossClient.getObject(bucketName, objectName);

// 读取文件内容。
System.out.println("Object content:");
BufferedReader reader = new BufferedReader(new InputStreamReader(ossObject.getObjectContent()));
while (true) {
    String line = reader.readLine();
    if (line == null) break;

    System.out.println("\n" + line);
}
// 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
reader.close();

// 关闭OSSClient。
ossClient.shutdown();
		

ossObject.getObjectContent()这个返回的是一个InputStream,是一个字节流。

然后用InputStreamReader(该类从数据源读取字节并将其解码为使用指定的字符集的字符)转化为字符,然后加上缓冲。

这样读取我感觉有问题,我特意查了查资料如下:

字节流是一种执行8位字节输入和输出的机制,基本单元为字节;而字符流是Java中执行16位Unicode输入和输出操作的机制,基本单元为Unicode码元。

 

 

字节流是最基本的,采用ASCII编码;它通常用于处理二进制数据,它是按字节来处理的,实际上它可以处理任意类型的数据,但它不支持直接写入或读取Unicode码元。

字符流采用Unicode编码,它是按虚拟机的encode来处理,也就是要进行字符集的转化;它通常处理文本数据,它支持写入及读取Unicode码元。

这样按照例子读取后就一直乱码,我不知道是不是这里的原因,有没有大佬解释一下。

但是我改成了字节流读取就没有乱码问题了。

 public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = -1;
        while((len=inStream.read(buffer))!=-1){
            outStream.write(buffer,0,len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

好不容易写写代码,整了半天这个。

希望疫情早点过去吧,加油鸭。

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Spring Boot中实现OSS文件下载,你可以按照以下步骤进行操作: 1. 首先,你需要引入阿里云OSS的Java SDK依赖。在你的`pom.xml`文件中添加以下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.9.2</version> </dependency> ``` 2. 在Spring Boot的配置文件中,添加OSS相关的配置项,包括`accessKey`、`secretKey`、`endpoint`和`bucketName`等信息。 ```properties # OSS配置 spring.aliyun.oss.access-key=your-access-key spring.aliyun.oss.secret-key=your-secret-key spring.aliyun.oss.endpoint=your-endpoint spring.aliyun.oss.bucket-name=your-bucket-name ``` 3. 创建一个用于处理文件下载的Controller。在该Controller中,注入`AliyunOSSClient`对象,并实现一个下载文件的接口。 ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.GetObjectRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.InputStream; import java.net.URLEncoder; @RestController @RequestMapping("/files") public class FileController { @Autowired private OSS ossClient; @Value("${spring.aliyun.oss.bucket-name}") private String bucketName; @GetMapping("/{fileName}") public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) throws Exception { // 构造OSS文件下载请求 GetObjectRequest request = new GetObjectRequest(bucketName, fileName); // 下载文件流 InputStream inputStream = ossClient.getObject(request).getObjectContent(); // 设置文件下载响应头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8")); // 返回文件下载响应 return ResponseEntity .ok() .headers(headers) .body(new InputStreamResource(inputStream)); } } ``` 在上述代码中,`/{fileName}`表示下载文件的URL路径,`fileName`是要下载的文件名。 注意:上述代码中的`ossClient`对象需要通过Spring Bean配置来创建,并且需要在应用启动时初始化。 4. 配置OSS客户端的Bean。在你的Spring Boot应用的配置类中,添加以下内容: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OSSConfig { @Value("${spring.aliyun.oss.endpoint}") private String endpoint; @Value("${spring.aliyun.oss.access-key}") private String accessKey; @Value("${spring.aliyun.oss.secret-key}") private String secretKey; @Bean public OSS ossClient() { return new OSSClientBuilder().build(endpoint, accessKey, secretKey); } } ``` 在上述配置类中,通过`@Value`注解获取配置文件中的OSS相关配置项,然后创建并返回一个`OSS`对象。 这样,当访问`/files/{fileName}`接口时,就会触发文件下载操作。 需要注意的是,上述代码中的配置项需要根据你自己的阿里云OSS账号进行相应的配置。另外,还需要确保你的Spring Boot应用能够访问到正确的OSS服务。 希望以上信息能够帮助到你实现Spring Boot中的OSS文件下载功能!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值