java8:obsclient下载文件,restful风格

以下是一个使用 Spring Boot 实现的 RESTful 风格的 Controller 代码示例,用于实现从对象存储中下载文件并返回给前端:
import com.obs.services.ObsClient;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
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.RestController;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
public class DownloadController {

    @GetMapping("/download/{bucketName}/{objectKey}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String bucketName, @PathVariable String objectKey) {
        // 你的访问密钥、秘密密钥和终端节点
        String accessKey = "your_access_key";
        String secretKey = "your_secret_key";
        String endpoint = "your_endpoint";

        ObsClient obsClient = new ObsClient(accessKey, secretKey, endpoint);

        try {
            GetObjectRequest request = new GetObjectRequest(bucketName, objectKey);
            ObsObject obsObject = obsClient.getObject(request);

            // 从 objectKey 中提取文件名
            String fileName = extractFileName(objectKey);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);

            return new ResponseEntity<>(obsObject.getObjectContent().readAllBytes(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        } finally {
            obsClient.close();
        }
    }

    private static String extractFileName(String objectKey) {
        Pattern pattern = Pattern.compile("/folder/(.+)");
        Matcher matcher = pattern.matcher(objectKey);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "unknown_file";
    }
}
在这个示例中,通过/download/{bucketName}/{objectKey}路径可以触发下载操作,传入桶名和对象键。代码会从对象存储中获取文件,并设置合适的响应头将文件返回给前端。

请记得将代码中的your_access_key、your_secret_key和your_endpoint替换为你的实际值。同时,如果对象键的格式不固定,可能需要调整正则表达式来提取文件名。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值