生成临时访问文件的URL:
生成临时访问文件的URL: 如何使用STS以及签名URL临时授权访问OSS资源(Java)_对象存储 OSS-阿里云帮助中心
//文件的全路径
String filekey = fileInfo.getString("filePath");
OSS ossClient = new OSSClientBuilder().build("oss-cn-shanghai.aliyuncs.com", ossAccessKeyId, ossSecretAccessKey);
try {
Date expiration = new Date(new Date().getTime() + 3600 * 1000);
// 填写Bucket名称,例如examplebucket。
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucket, filePath);
//设置过期时间s
request.setExpiration(expiration);
//方法一: 直接覆盖请求头
ResponseHeaderOverrides Headers = new ResponseHeaderOverrides();
Headers.setContentDisposition(String.format("attachment;filename=%s", fileInfo.getString("fileName") + "." + fileInfo.getString("extensionName")));
request.setResponseHeaders(Headers);
URL u = ossClient.generatePresignedUrl(request);
return CommonResVo.success(u);
} catch (OSSException oe) {
log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
log.error("Error Message:" + oe.getErrorMessage());
log.error("Error Code:" + oe.getErrorCode());
log.error("Request ID:" + oe.getRequestId());
log.error("Host ID:" + oe.getHostId());
throw new BaseException(oe.getErrorMessage());
} catch (ClientException ce) {
log.error("Caught an ClientException, which means the client encountered a serious internal problem while trying to communicate with OSS, such as not being able to access the network.");
log.error("Error Message:" + ce.getMessage());
throw new BaseException(ce.getErrorMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
<—————————————————以下都是废话—————————————————>
W3c标准,浏览器请求头不允许传 Date,所以以下方案废了
官方文档地址:使用REST API发起请求_对象存储 OSS-阿里云帮助中心
如果OSS文件设置保护,需要鉴权才能访问,添加请求头鉴权,SDK方法如上;
将鉴权信息和地址、时间返回给前端,前端直接从oss上读取
String filePath = "/admin/2023/6/183569314928918546.png"; RequestMessage requestMessage = new RequestMessage("sl-ops-oss", filePath); SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US); Calendar cd = Calendar.getInstance(); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT String str = sdf.format(cd.getTime()); System.out.println(str); Map<String, String> headers = new HashMap<>(); headers.put("Date", str); requestMessage.setHeaders(headers); String signature = SignUtils.buildSignature(ossSecretAccessKey, "GET", "/" + bucket + "/" + filePath, requestMessage); String Authorization = SignUtils.composeRequestAuthorization(ossAccessKeyId, signature); JSONObject jsonObject = new JSONObject(); jsonObject.put("Date", str); jsonObject.put("Authorization", Authorization); jsonObject.put("url", String.format(url, bucket) + filePath);