如何发送图像和JSON形成Angular httpClient

问题描述 投票:1回答:1

我想向服务器发送一个带有一个请求的图像和JSON。这是我的JS代码,我想用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!");
      });;
    }
javascript angular
1个回答
0
投票

您可以将图像作为String发送,使用Base64将图像转换为String,然后在Json中发送它。看看这个:Converting an image to base64 in angular 2

© www.soinside.com 2019 - 2024. All rights reserved.