Failed to set the ‘value’ property on ‘HTMLInputElement’

  • Post author:
  • Post category:其他


最近使用 Angular 进行图片上传时碰到这个问题

在这里插入图片描述

这是我页面的代码,使用的是 angular 6 版本:

在这里插入图片描述

百度了一下,原因是出于安全限制,file 的value 是只读的,只能由用户选择或手动输入,不允许由程序代码设置,所以在JS中修改 file 的 value 会爆出此错误信息。但是在网上百度一堆发现都是jQuery的解决方法并没有找到使用 angular 的,只好翻墙去 google。最后在 https://github.com/angular/angular/issues/6074 找到了解决方法,

在这里插入图片描述

只需去掉 [(ngModel)] 双向绑定,然后在JS中把值绑定一下就可以了,特意在此记录一下。

HTML代码如下

<div class="rowTabsOneDiv rowTabsOneDiv-full-width rowTabsOneDiv-tall-height">
	<span>圖像:</span>
	<section class="gz-full-img">
		<img *ngIf="frontImgOp" src="{{modelTwoChild.productOptionImagePath}}" />
		<img *ngIf="!frontImgOp" [src]="frontImg.src" (click)="selectImg(frontImgFile)" />
		<input class="file" type="file" #frontImgFile (change)="this.value=imgChange($event, frontImg)"/>
	</section>
</div>

TS代码如下

selectImg(img) {
	img.click();
}
async imgChange(event, imgObj) {
	const files = event && event.target && event.target.files;
	if (files) {
		try {
			const _result: any = await this._getImgB64(files[0]);
			this.modelTwoChild.productOptionImage = _result.b64img;
			imgObj.src = _result.b64img;
			const _fileInfo = _result.fileInfo;
			imgObj.name = _fileInfo.name;
			this.modelTwoChild.productOptionImageName = _fileInfo.name;
			if (this.modelTwoChild.productOptionImageName.length > 50) {
				const name = this.modelTwoChild.productOptionImageName;
				const ext = name.substring(name.lastIndexOf('.'));
				const file = name.substring(0, 50 - ext.length);
				this.modelTwoChild.productOptionImageName = file + ext;
			}
		} catch (e) {
			console.log(e);
		}
	}
	this.frontImgOp = false;
}
private _getImgB64(file: any) {

	const reader = new FileReader();
	const fileInfo = {
		lastModified: file.lastModified,
		name: file.name,
		size: file.size,
		type: file.type,
		action: file.action,
		width: file.width,
		height: file.height
	};
	const that = this;

	return new Promise((resolve, reject) => {
		reader.onload = function (re) {
			const model = re;
			that.functionBase64(model.target.result);
			resolve({
				b64img: ( < any > re.target).result,
				fileInfo: fileInfo,
			});
		};
		reader.readAsDataURL(file);
	});
}
/*ba64成功回調 */
functionBase64(base64) {
	this.modelTwoChild.productOptionImageURL = base64;

}



版权声明:本文为qq_38426766原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。