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替换为你的实际值。同时,如果对象键的格式不固定,可能需要调整正则表达式来提取文件名。