如何解决如何在 Angular 和 Ionic 中以编程方式删除 UploadCare 中的文件?
我在我的项目中使用了 Angular、Ionic 和 Firebase。我使用 Uploadcare 将照片上传和检索到应用程序。我可以删除数据库中的文件,但问题是实际图像仍上传到 UploadCare 存储中。
这是我的代码:
organization.service.ts - 这是我在 Firebase 和 UploadCare 中连接应用程序的地方
我得到的答复:
更新
网络响应:
这是我在删除带有图像的项目时的网络活动。
organization.service.ts
deleteOrg(orgId: string){
return this.http
.delete(`https://db-student-portal-default-rtdb.firebaseio.com/add-organization/${orgId}.json`)
.pipe(switchMap(() => {
return this.allOrg;
}),take(1),tap(orgs => {
this.organization.next(orgs.filter(o => o.id !== orgId))
})
);
}
//This is the function to delete the image in UploadCare
deleteImage(image: any){
let httpHeader = new HttpHeaders();
httpHeader.set('Authorization',`Uploadcare.Simple ${PUB_KEY}:${SEC_KEY}`);
httpHeader.set('Accept','application/vnd.uploadcare-v0.5+json');
this.http.delete(`https://api.uploadcare.com/files/${image}/`,{headers: httpHeader});
}
organization.page.ts
onDeleteOrg(){
this.alertCtrl.create({
header: 'Delete ' + this.loadedOrg.orgName,message: 'Do you want to delete this organization?',buttons: [
{
text: 'Cancel',role: 'cancel'
},{
text: 'Delete',handler: () => {
this.loadingCtrl.create({
message: 'Deleting Organization: ' + this.loadedOrg.orgName,spinner: 'circular'
}).then(loadEl => {
loadEl.present();
//THIS IS WHERE THE DELETION HAPPEN (in the Firebase)
this.orgService.deleteOrg(this.loadedOrg.id).subscribe(() => {
//THIS IS WHERE THE DELETION HAPPEN (in the UploadCare)
this.orgService.deleteImage(this.loadedOrg.imageUrl.replace('https://ucarecdn.com/',''));
loadEl.dismiss();
this.router.navigate(['/homepage']);
});
});
}
}]
}).then(alertEl => {
alertEl.present();
});
}
解决方法
根据文档,UploadCare 的单个文件删除只需要文件的 UUID,即 delete /files/:uuid
(参见 https://uploadcare.com/docs/rest-api/accessing-files/#delete-file)。
据我所知,您正在尝试将整个文件数据传递给 API,这在语义上无论如何都不正确(它使用 uuid 来匹配正确的文件)。
将您的代码调整为类似的内容
let httpHeaders = new HttpHeaders();
httpHeaders.set('Authorization','Uploadcare.Simple');
httpHeaders.set('UPLOADCARE_PUB_KEY','6b*****************7');
this.httpClient.delete(`https://api.uploadcare.com/files/${uuid}/`,{ headers: httpHeaders })
应该可以解决问题。
编辑:我觉得需要更多解释。您尝试使用代码执行的操作是调用 UploadCare 的 delete
端点。根据文档,该端点需要被删除文件的 uuid,即 /files/:uuid
以及 Authorization
和 UPLOADCARE_PUB_KEY
标头。为此,您使用 HttpHeaders
。
在您的版本中,您将该数据作为 FormData
对象(请参阅 docs)的一部分传递,我想这应该会引发 HTTP404 错误。
Simple
授权方案要求您提供公开和秘密 API 密钥(请参阅 Uploadcare REST API reference)。你应该这样修改你的代码
let httpHeaders = new HttpHeaders();
httpHeaders.set('Authorization',`Uploadcare.Simple ${YOUR_PUBLIC_KEY}:${YOUR_SECRET_KEY}`);
httpHeaders.set('Accept','application/vnd.uploadcare-v0.5+json');
this.httpClient.delete(`https://api.uploadcare.com/files/${uuid}/`,{ headers: httpHeaders });
请注意,在前端实现文件删除逻辑是不安全的,不推荐使用,因为它会暴露您的密钥。您应该在应用的后端实现它,这样应用的用户就无法访问包含密钥的请求详细信息,或使用基于令牌的 Uploadcare auth scheme。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。