[英]Angular 4/5 file upload or image upload to Amazon S3
我正在尝试在我的MEAN应用程序中实现文件上传。 我的后端(Node和Express)和前端(Angular)是分开部署的。 我需要的是通过Angular将文件上传到amazon s3,成功上传后获取地址目的地然后将文件目的地保存到变量。
有没有简单的方法来实现这个? 假设我有一个这样的表格
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input type="file" id="myImage" (change)="onFileChange($event)" #fileInput>
<hr>
<div class="text-right">
<button type="submit" class="btn btn-primary">Actualizar perfil</button>
</div><br>
</form>
然后这个代码将在我的组件上(仅用于测试我可以获取文件)
@ViewChild('fileInput') fileInput: ElementRef;
createForm() {
this.form = this.formBuilder.group({
'myImage': null
});
}
onFileChange(event) {
let reader = new FileReader();
if(event.target.files && event.target.files.length > 0) {
let file = event.target.files[0];
reader.readAsDataURL(file);
reader.onload = () => {
this.form.get('myImage').setValue({
filename: file.name,
filetype: file.type,
value: reader.result.split(',')[1]
})
};
}
}
onSubmit() {
const formModel = this.form.value;
this.loading = true;
setTimeout(() => {
console.log(formModel);
alert('Finished uploading');
this.loading = false;
}, 1000);
}
如何将文件从我的表单发送到Amazon S3? 然后在亚马逊s3中获取文件目的地,这样我就可以将它保存到我的数据库中以便稍后获取它。 我也不确定我是否应该在我的后端或前端创建亚马逊s3配置,我现在很困惑。
如果可以,请尽量避免在浏览器中使用AWS SDK,因为您无法对使用率进行评级。 或者更糟糕的是,如果您在前端存储访问密钥,则可以公开您的AWS凭据。
相反,在node.js后端使用AWS SDK并将API公开为代理。 请参阅https://aws.amazon.com/sdk-for-node-js/ 。
您应该使用AWS SDK for JavaScript。
您可以在此处查看上传照片的示例。
function addPhoto(albumName) {
var files = document.getElementById('photoupload').files;
if (!files.length) {
return alert('Please choose a file to upload first.');
}
var file = files[0];
var fileName = file.name;
var albumPhotosKey = encodeURIComponent(albumName) + '//';
var photoKey = albumPhotosKey + fileName;
s3.upload({
Key: photoKey,
Body: file,
ACL: 'public-read'
}, function(err, data) {
if (err) {
return alert('There was an error uploading your photo: ', err.message);
}
alert('Successfully uploaded photo.');
viewAlbum(albumName);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.