我正在尝试上传文件,然后将其转换为base64字符串并添加到对象。但它似乎没有用。 console.log()每次显示空对象
<input type="file" (change)="onChange($event)" accept="image/jpeg, image/png" />
<input type="submit" value="send" (click)="upload()" />
功能:
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
reader.readAsDataURL(image);
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
}
upload() {
console.log(this.product);
}
答案 0 :(得分:1)
这对我有用...希望有所帮助
uploadFileImage(fileInput: any)
{
var files = fileInput.target.files;
var file = files[0];
if (files && file)
{
var reader = new FileReader();
reader.onload = function(readerEvt: any)
{
var binaryString = readerEvt.target.result;
var base64 = btoa(binaryString);
this.product.photos = [];
this.product.photos.push(base64);
};
reader.readAsBinaryString(file);
}
}
答案 1 :(得分:1)
这里有一件事是,只有当reader.readAsDataURL()成功加载文件时才会调用reader.onload。从逻辑上讲,它不应该写在reader.onload中。在onload函数之外使用readAsDataURL,使其保持在onChange函数内。然后它应该工作。您的代码应该如下所示。
onChange(fileInput: any) {
let image: any = fileInput.target.files[0];
let reader: FileReader = new FileReader();
reader.onload = () => {
let photo: AddPhoto = new AddPhoto();
photo.base64Image = reader.result;
this.product.photos = [];
this.product.photos.push(photo);
};
reader.readAsDataURL(image);
}