public void downLoad(String bucketName, String objectName, HttpServletResponse httpServletResponse) {
// 創建ObsClient實例
final ObsClient obsClient = new ObsClient(ak, sk, endPoint);
ObsObject obsObject = obsClient.getObject(bucketName, objectName);
try {
// 讀取對象內容
System.out.println("Object content:");
@Cleanup
InputStream input = obsObject.getObjectContent();
@Cleanup
OutputStream outputStream = httpServletResponse.getOutputStream();
byte[] b = new byte[1024];
@Cleanup
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
while ((len = input.read(b)) != -1) {
bos.write(b, 0, len);
}
outputStream.write(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
}
如果需要下載 設置響應頭
/**
* 查看圖片 下載
*
* @param httpServletResponse
*/
@RequestMapping("/openImage/{fileid}")
public void openImage(@PathVariable("fileid") Integer fileid, HttpServletResponse httpServletResponse) {
OutputStream outputStream = null;
BlockFile blockFile = blockFileService.getById(fileid);
// byte[] bytes = blockChainCallService.downLoad("/api/file/download?file_id=76084");
BlockDownLoadDto blockDownLoadDto = blockChainCallService.downLoad(blockFile.getUrl());
try {
outputStream = httpServletResponse.getOutputStream();
httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + blockDownLoadDto.getPrefix() + "." + blockDownLoadDto.getSuffix());
httpServletResponse.setHeader("Accpet-Ranges", "bytes");
httpServletResponse.setHeader("Content-Length", "number");
httpServletResponse.setContentType("application/octet-stream");
outputStream.write(blockDownLoadDto.getBytes());
// outputStream.write(blockFileService.pdfAddWaterMark(blockDownLoadDto.getBytes()));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}