从下载输出流COSObjectInputStream获取的图片数据错误
kelincxm opened this issue · 1 comments
kelincxm commented
依赖
SpringBoot 2.4.2
cos_api 5.6.105
WebController
@RestController
public class WebController {
@GetMapping("/download")
public void downloadFile(HttpServletResponse response) {
COSUtil.downloadFileByInputStream("img/flower.png", response);
}
}
COSUtil
@Slf4j
public class COSUtil {
private static final String SECRET_ID = "XXX";
private static final String SECRET_KEY = "XXX";
private static final String APPID = "XXX";
private static final String BUCKET_NAME = "XXX-" + APPID;
private static final String LOCATION_NAME = "XXX";
public void downloadFileByInputStream(String remotePath, HttpServletResponse response) {
COSCredentials credentials = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
ClientConfig clientConfig = new ClientConfig(new Region(LOCATION_NAME));
COSClient cosClient = new COSClient(credentials, clientConfig);
GetObjectRequest getObjectRequest = new GetObjectRequest(BUCKET_NAME, remotePath);
COSObject cosObject = cosClient.getObject(getObjectRequest);
try (COSObjectInputStream cosObjectInput = cosObject.getObjectContent()) {
byte[] buffer = new byte[cosObjectInput.available()];
ServletOutputStream outputStream = response.getOutputStream();
int read = cosObjectInput.read(buffer);
while (read != -1) {
outputStream.write(buffer);
outputStream.flush();
read = cosObjectInput.read(buffer);
}
} catch (IOException e) {
log.error(e.getMessage());
}
cosClient.shutdown();
}
}
原图
浏览器访问图片
Jeffreykzli commented
您好,通过您的描述暂时没法准确定位到问题,您可以提交工单,提供request ID等信息便于我们进一步分析问题原因