【问题标题】:How to upload an image to the ASP.NET CORE WEB API in BYTE ARRAY format using React JS, 400 bad request如何使用 React JS 以 BYTE ARRAY 格式将图像上传到 ASP.NET CORE WEB API,400 错误请求
【发布时间】:2021-01-27 23:53:24
【问题描述】:

我们正在尝试将一些数据发送到 ASP.NET CORE WEB API 服务器并使用 React 中的 axios post 请求将该数据上传到网站,主要问题是将 BYTE ARRAY 格式的图像发送到服务器。服务器仅接受 BYTE ARRAY 格式的图像。它给了我们一个错误 POST 400。 Upload.jsx:47 错误:请求失败,状态码为 400。请帮助。这是我们使用 react hooks 的代码:

import React, { useState } from "react";
import axios from "axios";

const Upload = () => {
  const [upload, setUpload] = useState({
    ruName: "",
    azName: "",
    kaName: "",
    enName: "",
    image: null,
    shopId: localStorage.getItem("shopId")
  });

  const changeHandler = e => {
    setUpload({ [e.target.name]: e.target.value });
  };

  const uploadHandler = async e => {
    const base64 = await convertBase64(e.target.files[0]);
    setUpload({ image: base64 });
  };

  const convertBase64 = file => {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);

      fileReader.onload = () => {
        resolve(fileReader.result);
      };

      fileReader.onerror = error => {
        reject(error);
      };
    });
  };

  const onAddCategory = async e => {
    e.preventDefault();
    try {
      const res = await axios.post(
        "https://midamoapi.ge/api/productcategories/",
        upload
      );
      console.log(res);

    } catch (err) {
      console.log(err);
    }
  };

  console.log(upload);

  return (
    <div className="container-add">
      <input name="ruName" onChange={changeHandler} type="text" />
      <input name="azName" onChange={changeHandler} type="text" />
      <input name="enName" onChange={changeHandler} type="text" />
      <input name="kaName" onChange={changeHandler} type="text" />
      <input name="image" type="file" onChange={uploadHandler} />
      <button className="btn" onClick={onAddCategory}>
        Submit
      </button>
    </div>
  );
};

export default Upload;

【问题讨论】:

  • 嗨@GreatData,关于这个案例的任何更新?如果回复确实有助于解决问题,您可以accept it as answer

标签: javascript arrays reactjs asp.net-core asp.net-core-webapi


【解决方案1】:

请求失败,状态码 400

在您的代码中,我们可以发现您使用FileReader.readAsDataURL() 来获取所选图像的base64 编码字符串,然后将数据发布到您的操作方法。

请检查您的操作方法和接受的参数是否如下所示。

类别类

public class Category
{
    public string RuName { get; set; }
    public string AzName { get; set; }
    public string EnName { get; set; }
    public string KaName { get; set; }
    public string Image { get; set; }  //please note that Image property is string type
    public int ShopId { get; set; }
}

动作方法

[HttpPost]
public IActionResult AddCategory(Category category)
{
    //...
    //your code logic here

测试结果

另外,如果您想使用IFormFile处理或保存图像文件,您可以尝试通过FormData传递数据,而不是通过请求正文传递json格式的数据。

【讨论】:

    猜你喜欢
    • 2019-08-07
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 2020-11-13
    • 2021-09-05
    • 1970-01-01
    • 2015-11-28
    • 2018-06-24
    相关资源
    最近更新 更多