oss 下载文件 并把文件返回前端
时间: 2024-06-10 15:06:35 浏览: 279
可以使用阿里云提供的 Object Storage Service (OSS) SDK,在后端通过 API 下载文件并返回给前端。以下是简单的示例代码:
```
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
@Service
public class OssService {
@Value("${oss.endpoint}")
private String endpoint;
@Value("${oss.accessKeyId}")
private String accessKeyId;
@Value("${oss.accessKeySecret}")
private String accessKeySecret;
@Value("${oss.bucketName}")
private String bucketName;
public ResponseEntity<Resource> downloadFile(String objectName) {
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, objectName);
InputStream inputStream = ossClient.getObject(getObjectRequest).getObjectContent();
InputStreamResource resource = new InputStreamResource(inputStream);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION,
"inline;filename*=UTF-8''" + URLEncoder.encode(objectName, "UTF-8"));
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
headers.setContentLength(Long.parseLong(getObjectRequest.getResponseHeaders().get("Content-Length").get(0)));
return ResponseEntity.ok().headers(headers).body(resource);
}
}
```
在这个例子中,我们通过`OSS`对象的`getObject`方法下载文件,将文件转换为`InputStream`,将其作为响应体返回给前端。要将文件名作为响应头,在这里使用了`Content-Disposition`和`filename*`参数。注意,需要使用`URLencoder`进行URL编码,以避免中文乱码问题。
阅读全文