【问题标题】:How to stop/prevent redirection when uploading image in Angular在Angular中上传图像时如何停止/防止重定向
【发布时间】:2020-01-10 08:14:23
【问题描述】:
我已经实现了以角度上传图像的代码,但我在上传图像时卡住了,但是表单重定向到下面位置指定的 url 是我的代码,请帮忙。
<form #form action="http://localhost:8084/api/admin/product/images"
enctype="multipart/form-data" method="POST" >
<input type="file" name="myFile" id="myFile" required multiple />
<input type="submit" (click)="form.submit()" class="btn btn-primary"
value="Upload" />
</form>
我想上传图片,但用户应该留在同一页面上不要重定向
【问题讨论】:
标签:
javascript
html
node.js
angular
【解决方案1】:
更好的解决方案:
在 Angular 中,我们通常以更聪明的方式来做。
在component.html中:
<form>
<input type="file" name="myFile" id="myFile" (click)="onImageChanged($event)"/>
<input type="submit" (click)="submit()" class="btn btn-primary" value="Upload" />
</form>
在component.ts中:
export class AppComponent {
constructor(private http: HttpClient) { }
name = 'Angular';
selectedImage: File;
onImageChanged(event) {
const temp = event.target.files[0];
this.selectedImage = temp;
}
submit(event) {
const uploadData = new FormData();
uploadData.append('image', this.selectedImage, this.selectedImage.name);
this.http.post(`"http://localhost:8084/api/admin/product/images`, uploadData).subscribe();
}
}
那么你就不会遇到这样的重定向问题了。
变通解决方案:
您可以使用没有宽度和高度的 iframe,并将表单定位到此 iframe。
<iframe width="0" height="0" border="0" name="dummyframe" id="dummyframe"></iframe>
<form #form action="http://localhost:8084/api/admin/product/images"
enctype="multipart/form-data" method="POST" target="dummyframe">
<input type="file" name="myFile" id="myFile" required multiple />
<input type="submit" (click)="form.submit();submit($event)" class="btn btn-primary"
value="Upload" />
</form>