首页 > 解决方案 > 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",

},

标签: node.jsangularmongooseangular6httpclient

解决方案


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:

  1. Remove imgFront and imgBack from your productForm.
  2. Declare imgFront and imgBack properties on your Component.
  3. Disable the Submit button from the form unless the imgFront and imgBack are set.
  4. Once they are set, enable the submit button.
  5. While sending the response to the product API, add the imgFront and imgBack to the request payload as well.

Here's a Sample StackBlitz for your ref.


推荐阅读