简体   繁体   English

Angular httpClient如何发送图像和JSON

[英]How sent image and JSON form Angular httpClient

I want to send an image and JSON with one request to the server. 我想将一个请求的图像和JSON发送到服务器。 This is my JS code, I want to send with Angular. 这是我的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!");
      });;
    }

You could send the image as a String, convert the image to String using Base64 and then send it in the Json. 您可以将图像作为String发送,使用Base64将图像转换为String,然后在Json中发送。 take a look at this: Converting an image to base64 in angular 2 看一下这个: 将图像转换为角度2中的base64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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