【问题标题】:Null object error when reactJs file uploading using axios使用axios上传reactJs文件时出现空对象错误
【发布时间】:2021-06-21 21:35:29
【问题描述】:

我正在尝试使用 axios 上传图像,但它似乎总是为空,我无法修复它。发布请求通过 201 成功,但是当我发布请求表单前端时,这给出了空对象错误。我只是无法配置为什么会发生这种情况以及解决此问题的方法。

This is the error popup in the controller.

错误表示 ImageData 为空。我已将我的reactjs 代码连同此一起包含在内,以供您参考。 要提交的表单的一部分。

export default class Upload extends Component {
  constructor(props) {
    super(props);
    const pharmacyName = this.props.location.pharmacyName;
    this.state = {
      Date_time: "",
      Status: "",
      Status2: "",
      CustomerName: "",
      PatientName: "",
      PatientAge: 0,
      Address: "",
      Email: "",
      TeleNo: 0,
      Customer_id: 1,
      Pharmacy_id: 1,
      PharmacyName: pharmacyName ? pharmacyName : "",
      ImageData: null,
      Image:"",
      ImageSource: "",
    };
    this.changeHandler = this.changeHandler.bind(this);
  }

  changeHandler = (e) => {
    if (e.target.name === "ImageData") {
      this.setState({
        ImageData: URL.createObjectURL(e.target.files[0]),
      });
    } else {
      this.setState({ 
        [e.target.name]: e.target.value,
      });
    }
    console.log("final payload", this.state)
  };

  submitHandler = (e) => {
    console.log("e", e)
    e.preventDefault();
    console.log(this.state);
    axios
      .post('/api/Orders', this.state)
      .then((response) => {
        console.log(response);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    const {
      Date_time,
      Status,
      Status2,
      CustomerName,
      PatientName,
      PatientAge,
      Address,
      Email,
      TeleNo,
      Customer_id,
      Pharmacy_id,
      ImageData,
    } = this.state;
    return (
      <div className="outer">
        <div className="inner2">
          <form onSubmit={this.submitHandler}>
            <h3>Upload Your Prescription Below</h3>
           
              <input
                type="file"
                name="ImageData"
                placeholder="Upload Your Prescription Here"
                onChange={this.changeHandler}
              />

控制器:

public async Task<ActionResult<Order>> PostOrder([FromForm] Order order)
        {
            order.Image = await _iorderService.SaveImage(order.ImageData); //save image

            _context.Order.Add(order);
            await _context.SaveChangesAsync();

            return StatusCode(201);
        }
enter code here

模型类:

 public class Order
    {
        [Key]
        public int OrderID { get; set; }
        public DateTime Date_time { get; set; }
        public string Status { get; set; }
        public string Status2 { get; set; }
        public string PharmacyName { get; set; }
        public string CustomerName { get; set; }
        public string PatientName { get; set; }
        public int PatientAge { get; set; }
        public string Address { get; set; }
        public string Email { get; set; }
        public int TeleNo { get; set; }
        public int Customer_id { get; set; }

        
        public string Image { get; set;}

        [NotMapped]
        public IFormFile ImageData { get; set; }
        [NotMapped]
        public String ImageSource { get; set; }
        //[ForeignKey("Pharmacy")]
        public int Pharmacy_id { get; set; }
        //public Pharmacy Pharmacy { get; set; }
    }
}

OrderService.cs:

public class OrderService : IOrderService
    {
        private readonly IWebHostEnvironment _hostEnvironment;
        public OrderService(IWebHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }


        [NonAction]

        public async Task<string> SaveImage(IFormFile ImageData)
        {
            string imageName = new string(Path.GetFileNameWithoutExtension(ImageData.FileName).Take(10).ToArray()).Replace(' ', '-');
            imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(ImageData.FileName);
            var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, "Images", imageName);
            using (var fileStream = new FileStream(imagePath, FileMode.Create))
            {
                await ImageData.CopyToAsync(fileStream);
            }
            return imageName;
        }

        [NonAction]
        public void DeleteImage(String imageName)
        {
            var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, "Images", imageName);
            if (File.Exists(imagePath))
                File.Delete(imagePath);


        }
    }
}

IOrderService.cs:

{
    public interface IOrderService
    {
        Task<string> SaveImage(IFormFile ImageData);

        void DeleteImage(String imageName);
    }
}

【问题讨论】:

  • 嗨,你到底是从哪里得到这个错误的?您的描述是说这发生在 React 代码中,但是您的错误屏幕截图显示了不同的代码,这不是 React 代码。 “ImageData”在这里传递了什么?
  • 非常感谢您考虑我的问题。先生,此错误显示在此功能的控制器代码中。当我从前端发布请求时,此错误会在后端弹出。但是当我发布邮递员的请求时,没有任何问题。

标签: reactjs asp.net-core axios


【解决方案1】:

我正在尝试使用 axios 上传图像,但它似乎总是为空,我无法修复它。

ImageData: URL.createObjectURL(e.target.files[0])

公共异步任务 SaveImage(IFormFile ImageData)

请注意,URL.createObjectURL() 方法将返回指定 File 对象或 Blob 对象的对象 URL,您将该对象 URL 存储在 ImageData 并传递给接受 IFormFile 类型的后端 API 操作 SaveImage参数,这将导致发布的数据无法绑定到参数。

如果您想用选定的文件向SaveImage 端点发出请求,您可以直接存储e.target.files[0] 而不是存储对象 URL,然后用表单数据发出 HTTP 请求(填充选定的文件)从 reactJS 前端使用 axios 等。

【讨论】:

  • 要将文件从 reactJS、Angular 等前端上传到 WebAPI 后端,您可以参考这个 SO 线程:stackoverflow.com/questions/64854729/…
  • 先生,非常感谢您考虑我的问题。正如你所说,我改变了我的代码。但我仍然得到我之前得到的错误。我错过了什么吗? ImageData: e.target.files[0] 这是我改变的地方。
  • 您可以在浏览器开发工具“网络”选项卡中查看实际请求和发布的数据,并将其与邮递员发出的工作请求进行比较。
  • 先生,我仔细检查了邮递员请求和我通过实际请求发出的邮寄请求。一切都一样。我认识到的唯一问题是,在邮递员 ImageData: Capture.png 但在实际请求中它显示为 ImageData: File {name: "Capture.PNG", lastModified: 1616649095555, lastModifiedDate: Thu Mar 25 2021 10:41:35 GMT +0530(印度标准时间),webkitRelativePath: "", size: 140126, ...} 这是一个问题吗?难道我的 react js 代码错了?
  • 如果可能,您可以在浏览器开发者工具“网络”选项卡中分享您发布的数据的屏幕截图,以便我们更好地帮助解决问题。
猜你喜欢
  • 2020-08-07
  • 2020-10-13
  • 1970-01-01
  • 2020-10-02
  • 2020-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多