1

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!");
      });;
    }
Popovkov57
  • 179
  • 16
SIn san sun
  • 573
  • 4
  • 13
  • 31

1 Answers1

0

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

Jon Fernandez
  • 117
  • 1
  • 8