我正在使用带有图像上传选项的角度应用程序,
HTML:
<label class="hoverable" for="fileInput">
<img [src]="url ? url : avatarImage">
<div class="hover-text">Choose file</div>
<div class="background"></div>
</label>
<br/>
<input id="fileInput" type='file' (change)="onSelectFile($event)">
<button *ngIf="url" (click)="delete()" >delete</button>
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
如果用户单击图像,他可以选择并更新本地的图像,这就是我要拥有的。
以同样的方式,如果用户不希望更新个人资料图像,而是希望根据他/她的意愿选择任何头像图像,
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar.png">
<img (click)="uploadPersonaImage($event)" class="avatar-images" src="https://www.w3schools.com/howto/img_avatar2.png">
在ts中做了这样的事情,
uploadPersonaImage(e) {
this.url = e.target.src;
}
因此,在点击功能上,来自event.target
的src被设置为this.url
。
但是我需要将其转换为文件。.因为我需要将其作为文件发送给服务电话,所以我需要更新头像图像。
因此,请帮助我将用户选择/单击的头像图像转换为file/formdata
,以便可以将其作为文件格式发送到服务,并可以将其更新为用户选择的图像。.
示例: https://stackblitz.com/edit/angular-file-upload-preview-85v9bg
答案 0 :(得分:2)
您可以使用FormData附加读取的文件并将其发送到API。
onSelectFile(event) {
if (event.target.files && event.target.files[0]) {
this.uploadToServer(event.target.files[0]);
... rest of the code
}
uploadToServer(file) {
let formData: FormData = new FormData();
formData.append('fileName', file);
// call your api service to send it to server, send formData
}
编辑:
如果您在上传文件时无权触摸onSelectFile()
或触发其他功能,请尝试一下。
_url = ''
set url(val) {
this._url = val;
if (val) {
this.dataURLtoFile(val);
}
}
get url() {
return this._url;
}
uploadedImage: File ;
dataURLtoFile(dataurl) {
const arr = dataurl.split(',');
const mime = arr[0].match(/:(.*?);/)[1];
const imageExtension = mime.split('/')[1];
const bstr = atob(arr[1]);
let n = bstr.length;
const u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
this.uploadedImage = new File([u8arr], `uploaded.${imageExtension}`);
}
在您的API调用中,也许当您单击按钮时,
uploadPersonaImage(e) {
// this.apiService.someMethod(this.uploadedImage);
}
如果您想仅在上传图像时触发API调用,请将代码dataURLtoFile()
添加到uploadPersonaImage()
并从uploadPersonaImage()
设置器中调用url
说明
您了解event.target.src
是什么意思(将e
视为事件)吗?
此处event
表示您在点击时触发的点击/更改事件
点击上传照片。
event.target
表示发生事件的DOM元素。
event.target.src
将为您提供广告的src
属性值
触发变更事件的DOM元素。现在,您说行不通吗?不,不是因为您单击的元素是HTMLInputElement
,而是src
驻留在label
标记下的图像下。您打算如何致电uploadPersonaImage()
?什么叫你的方法?问了这么多次后,您还没有回答。
在上一次编辑中,我在url
的设置方法下添加了代码,该代码会将dataUrlFile
转换为实际的文件,这完全取决于服务器存储文件的方式。作为文件还是作为dataUrl?如果您想将其发送为文件,那么如果要保存为dataUrl,请按照我在答案中添加的转换进行操作,然后直接在API调用中保存this.url
的内容。