简体   繁体   中英

How sent image and JSON form Angular httpClient

I want to send an image and JSON with one request to the server. This is my JS code, I want to send with Angular.

function onSubmit(){

  var formData = new FormData();
  formData.append("file", document.forms["userForm"].file.files[0]);
  formData.append('user', new Blob([JSON.stringify({
    "firstName": document.getElementById("firstName").value,
    "lastName": document.getElementById("lastName").value})], 
    {type: "application/json"}));

   var boundary=Math.random().toString().substr(2);
   fetch('/api/cateogry/saveCategory', {
     method: 'post',
     body: formData}).then(function(response) {
       if (response.status !== 200) {
         alert("There was an error!");
       } else {
         alert("Request successful");
       }
      }).catch(function(err) {
        alert("There was an error!");
      });;
    }

You could send the image as a String, convert the image to String using Base64 and then send it in the Json. take a look at this: Converting an image to base64 in angular 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM