node.js - I want to upload an image URL to my angular form as json data and send it to server. the image URL is from the server response
问题描述
I want to upload an image URL to my angular form as json data and send it to server. the server should respond the image URL.
that because the server rename the image, I want to get the URL of the image from the server and then put it in the my form and then submit the form to server.
this is image upload to server:
selectedFile: File = null;
onFileSelected(event){
this.selectedFile = <File>event.target.files[0];
}
onUpload(){
const fd = new FormData();
fd.append('imageFile', this.selectedFile, this.selectedFile.name);
this.http.post('https://localhost:3443/products/upload', fd)
.subscribe(res => {
console.log(res);
});
}
and this is my form
createForm() {
this.productForm = this.fb.group({
name: ['', [Validators.required]],
imgFront: [''],
imgBack: [''],
});
and this is the json data
{
"name": "new product",
"imgFront": "images/products/0.7578449276506667Photo.png",
"imgBack": "images/products/0.44058320485375324WhatsApp Image 2018-10-25 at 18.00.23.jpeg",
},
解决方案
Generally, files are not considered as a part of the form. They are added to the form
but then handled differently. The reason is that file uploads are generally meant to be async and in most of the cases, aren't generally uploaded on form submit.
Instead, they are uploaded first and then their download URLs are added to the form value, just the way you want them.
So to handle your case, you can do the following:
- Remove
imgFront
andimgBack
from yourproductForm
. - Declare
imgFront
andimgBack
properties on your Component. - Disable the
Submit
button from the form unless theimgFront
andimgBack
are set. - Once they are set, enable the submit button.
- While sending the response to the product API, add the
imgFront
andimgBack
to the request payload as well.
Here's a Sample StackBlitz for your ref.
推荐阅读
- go - 在 Go 中,即使 []byte 是按值传递给方法的,但还是会修改原始值?
- react-native - 反应导航 5.0 未定义的参数
- dart - 分配非空值文字时的空安全类型提升
- android - 在 Kotlin Coroutine 的底层,同步是如何发生的?
- python - 了解 TensorFlow 模型输入
- c# - C# - 实体框架代码优先,延迟加载不起作用
- java - 带有标头的 GET 请求以打开 URL 并在 Angular 应用程序中检索标头
- ios - iOS:如何防止 UITextField 离开屏幕
- c - 不破坏复制/粘贴的子类编辑控件
- swift - 右键单击 UIKitForMac 的 UIButton(催化剂)