简体   繁体   English

如何使用 React JS 以 BYTE ARRAY 格式将图像上传到 ASP.NET CORE WEB API,400 错误请求

[英]How to upload an image to the ASP.NET CORE WEB API in BYTE ARRAY format using React JS, 400 bad request

We are trying to send some data to the ASP.NET CORE WEB API server and upload that data to a website using axios post request in React and the main problem is in sending image in BYTE ARRAY format to a server.我们正在尝试将一些数据发送到 ASP.NET CORE WEB API 服务器,并使用 React 中的 axios post 请求将该数据上传到网站,主要问题是将 BYTE ARRAY 格式的图像发送到服务器。 Server accepts images only in BYTE ARRAY format.服务器仅接受 BYTE ARRAY 格式的图像。 It gives us an error POST 400. Upload.jsx:47 Error: Request failed with status code 400. Please help.它给我们一个错误 POST 400。Upload.jsx:47 错误:请求失败,状态码为 400。请帮忙。 Here is the our code using react hooks:这是我们使用 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;

Request failed with status code 400请求失败,状态码 400

In your code, we can find that you use FileReader.readAsDataURL() to get a base64 encoded string of the selected image, then post the data to your action method.在您的代码中,我们可以发现您使用FileReader.readAsDataURL()获取所选图像的 base64 编码字符串,然后将数据发布到您的操作方法。

Please check if your action method and accepted parameter look like below.请检查您的操作方法和接受的参数是否如下所示。

Category class类别类

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; }
}

Action method动作方法

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

Test Result测试结果

在此处输入图片说明

Besides, if you'd like to process or save the image file using IFormFile , you can try to pass the data via FormData rather than in json format data through request body.此外,如果您想使用IFormFile处理或保存图像文件,您可以尝试通过FormData传递数据,而不是通过请求正文传递 json 格式的数据。

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

相关问题 asp.net MVC 大字节大小文件在尝试上传图像时返回 400 Bad Request - asp.net MVC large byte size files returns a 400 Bad Request when trying to upload image 将数据发布到 asp.net 核心 web api 和 Z80FBDBB37CED758 中的 FormData 时出现“400 bad request” - “400 bad request” when posting data to asp.net core web api with FormData in XmlHttpRequest 如何使用croppie js裁剪图像并上传到asp.net核心 - How to crop image using croppie js and upload in asp.net core 未处理 Web API 请求 Asp.net Core 3.1 和 Axios - Web API Request not processed Asp.net Core 3.1 and Axios ASP .NET MVC核心WEB API上传文件使用Angular JS显示错误 - ASP .NET MVC Core WEB API upload file showing error using Angular JS 将JSON数组集合发布到Asp.net Core Web API - Posting JSON Array Collection to Asp.net Core Web API 如何在 CKEditor 5 中使用 asp.net core razor Pages 上传图片 - How upload image in CKEditor 5 With asp.net core razor Pages 如何在angularjs中上传带有一些参数的图像。 和asp.net web api - How to upload image with some parameters in angularjs. and asp.net web api 尝试使用 MERN 上传图像时出现 400 错误请求错误 - Trying to upload an image using MERN getting 400 bad request error 错误请求错误:使用 axios 放置的 React js 中的 400 - Bad Request error: 400 in React js using axios put
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM