Angular14更新产品表单时旧图片消失报404错误求助
问题解决:选择新图片后旧图片显示断裂图标并报404错误
问题原因
选择新图片时,你通过patchValue把File对象赋值给了表单的image字段,而原本这个字段存储的是服务器上的图片路径字符串。当模板尝试调用bookForm.value.image.toString()时,File对象的toString()方法会返回[object File],导致生成的图片URL变成http://localhost:3000/[object%20File],服务器找不到这个资源,所以报404错误。
解决方案
步骤1:单独存储旧图片路径
在组件中新增变量存储原始图片路径,避免被File对象覆盖:
oldImageUrl?: string; bookForm!: FormGroup; ngOnInit(): void { const bookData = this.service.bookGetter(); this.oldImageUrl = bookData?.image; // 保存旧图片路径 this.bookForm = new FormGroup({ _id: new FormControl(bookData?._id), name: new FormControl(bookData?.name, [Validators.required]), author: new FormControl(bookData?.author, [Validators.required]), price: new FormControl(bookData?.price, [Validators.required]), image: new FormControl(bookData?.image, [Validators.required]), }); }
步骤2:修改旧图片展示模板
使用单独存储的oldImageUrl展示旧图片,并且在选择新图片后隐藏旧图片:
<span class="text-center text-[1.25rem] text-green-600 font-bold mb-[-2rem]" > Current Image </span> <!-- 仅当未选择新图片时显示旧图片 --> <img *ngIf="oldImageUrl && !(bookForm.get('image')?.value instanceof File)" src="http://localhost:3000/{{ oldImageUrl.replace('./assets', '') }}" alt="Current Book Image" class="p-[0.5rem] h-[300px] w-[300px]" />
优化:选择新图后顶部显示预览
如果希望选择新图片后,顶部直接显示预览图而非隐藏,可以修改模板如下:
<span class="text-center text-[1.25rem] text-green-600 font-bold mb-[-2rem]" > Current Image </span> <!-- 无预览图时显示旧图片,有预览图时显示新图预览 --> <img *ngIf="!imagedata" src="http://localhost:3000/{{ oldImageUrl.replace('./assets', '') }}" alt="Current Book Image" class="p-[0.5rem] h-[300px] w-[300px]" /> <img *ngIf="imagedata" [src]="imagedata" alt="New Book Image Preview" class="p-[0.5rem] h-[300px] w-[300px]" />
额外说明
提交表单时,需要区分image字段是原始路径还是File对象:如果是File对象,需要用FormData上传;如果还是字符串,说明用户没换图片,直接提交路径即可。
内容的提问来源于stack exchange,提问作者M Nouman
相关产品推荐
相关产品推荐

