更具阿里云oss文档:https://help.aliyun.com/document_detail/31926.html?spm=a2c4g.11174283.6.1330.142a7da2rCJayF
文档介绍说上传的几种方式,
采用JavaScript客户端直接签名(参见JavaScript客户端签名直传)时,AccessKeyID和AcessKeySecret会暴露在前端页面,因此存在严重的安全隐患。因此,OSS提供了服务端签名后直传的方案。
服务端签名后直传的原理如下:
所以要对应服务端获取签名授权,
注意我通过服务端接口,返回需要的字段;
'key' : g_object_name,
'policy': policyBase64,
'OSSAccessKeyId': accessid,
'success_action_status' : '200', //让服务端返回200,不然,默认会返回204
'callback' : callbackbody,
'signature': signature,
};
以上返回的字段,需要post formdata 传给oss服务器
控件说明:https://ng.ant.design/components/upload/zh
HTML代码
<nz-upload [nzMultiple]="true" [nzCustomRequest]="customReq" (nzChange)="handleChange($event)">
<button nz-button><i nz-icon nzType="upload"></i><span>Click to Upload</span></button>
</nz-upload>
Typescript代码:
customReq = (item: UploadXHRArgs) => {
//获取服务器Policy
this.httpClient.get('/AliyunOSS/GetPolicy', {}).subscribe((res: ResponseDataModel) => {
console.log(res.data);
const serve = res.data as ServerData;
// Create a FormData here to store files and other parameters.
const formData = new FormData();
formData.append('key', '/dir/' + item.file.name);
formData.append('bucket', serve.bucket);
// formData.append('x-oss-meta-tag', 'dummy_etag_' + file.name);
formData.append('OSSAccessKeyId', serve.OSSAccessKeyId);
formData.append('policy', serve.policy);
formData.append('Signature', serve.Signature);
// formData.append('callback', this.serve.callback);
formData.append('success_action_status', '200');
// tslint:disable-next-line:no-any
formData.append('file', item.file as any);
//设置cors跨域请求
const headerstemp = new HttpHeaders({ 'Access-Control-Allow-Origin': '*' });
console.log('------', formData.get('file'));
item.action = serve.host;
const req = new HttpRequest('POST', item.action!, formData, {
headers: headerstemp,
reportProgress: true, //进度条
// withCredentials: true
});
// Always returns a `Subscription` object. nz-upload would automatically unsubscribe it at correct time.
return this.http.request(req).subscribe(
(event: HttpEvent<{}>) => {
if (event.type === HttpEventType.UploadProgress) {
if (event.total! > 0) {
// tslint:disable-next-line:no-any
(event as any).percent = (event.loaded / event.total!) * 100;
}
item.onProgress!(event, item.file!);
} else if (event instanceof HttpResponse) {
item.onSuccess!(event.body, item.file!, event);
}
},
err => {
console.log(err);
item.onError!(err, item.file!);
}
);
});
};