【问题标题】:How sent image and JSON form Angular httpClient如何从 Angular httpClient 发送图像和 JSON
【发布时间】:2019-07-23 12:30:15
【问题描述】:

我想通过一个请求向服务器发送图像和 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!");
      });;
    }

【问题讨论】:

  • 面临的问题是什么?
  • 我想发送一张图片和 JSON 格式的 firstName,lastName。
  • 我在问你使用上面的代码时发生了什么?
  • 工作得很好,我支持图像和 JSON,但我想将 JS 代码转换为有角度的 httpClient 代码。

标签: javascript angular


【解决方案1】:

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

【讨论】:

  • 是的,我知道,但我不想作为 bas64 发送,我想在我的 JS 代码中喜欢这个。
猜你喜欢
  • 1970-01-01
  • 2015-11-04
  • 1970-01-01
  • 2020-03-12
  • 2019-07-31
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多