【问题标题】:How to upload image from React to ASP.NET Core Web API?如何将图像从 React 上传到 ASP.NET Core Web API?
【发布时间】:2019-08-07 20:43:16
【问题描述】:

我在 mt 服务器端有 Web API 控制器

[HttpPost("CreateImage")]
    public void CreateImage([FromBody] ImageDTO img)
    {
        Image image = new Image { FileName = img.FileName };
        byte[] imageData = null;
        using (var binaryReader = new BinaryReader(img.Image.OpenReadStream()))
        {
            imageData = binaryReader.ReadBytes((int)img.Image.Length);
        }
        image.Picture = imageData;

        imageRepo.Create(image);

    }

ImageDTO 在哪里

     public class ImageDTO
    {
        public string FileName { get; set; }

        public IFormFile Image { get; set; }
    }

像这样的Image.cs

public class Image
   {
      public int Id { get; set; }

      public string FileName{ get; set; }

      public byte[] Picture { get; set; }

      public List<User> Users { get; set; }
   }

这就是我在 React 客户端上用于处理和发送图像的方法:

<form>
        <p>
            <label>Аватар</label>
            <input name="Avatar" id = 'img' type="file" class="form-control" onChange={(e)=>this.handleImageChange(e)}/>
        </p>
        <p>
            <input type="submit" value="Добавить" onClick={this.sendImage}/>
        </p>
</form>
      <div className="imgPreview">
      {$imagePreview}
    </div>

处理文件进入状态的函数

    handleImageChange(e) {
    e.preventDefault();
    let form = new FormData();
    for (var index = 0; index < e.target.files; index++) {
      var element = e.target.files[index];
      form.append('file', element);
  }
    this.setState({file: form});
  }

发送到服务器

async sendImage(event) {
event.preventDefault();

console.log(this.state.file);
await addImage(this.state.file);
console.log('it works');}

addImage函数:

addImage = async ( image)  => {

    await fetch('https://localhost:44331/api/users/CreateImage',
        {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + sessionStorage.tokenKey
            },
             body:  JSON.stringify({
                FileName: 'Img',
                Image: image
            })
        }
    )
}

但是当它在服务器上发送请求时,它返回错误 400,这意味着“错误请求”。所以我认为这可能是发送的数据类型错误或类似的东西。也许有人看到了错误或可以修复的东西。或者有人可以展示一个将图像从 React 发送到 Web Api 服务器的工作示例。我需要你们的帮助!

【问题讨论】:

  • 您不能对二进制数据进行字符串化。您应该在请求的正文中发送 FormData
  • 我改变了我的控制器,所以它需要 ([FromForm]IFormFile 正文),但现在它得到一个空数据。
  • 我也从客户端发送 FormData。
  • 实际上它得到错误 500 但我认为这是因为空数据。
  • 在浏览器的开发者工具中查看发送到服务器的请求。

标签: c# reactjs image-uploading asp.net-core-webapi


【解决方案1】:

上传需要注意以下几点:

  1. 您需要使用formdataFromForm
  2. formdata 中的字段应与模型字段对应。

步骤:

  1. 更改控制器操作。

    public void CreateImage([FromForm] ImageDTO img)
    {
    
    }
    
  2. 客户代码:

    async sendImage(event) {
        event.preventDefault();
        console.log(this.state.file);
        await this.addImage(this.state.file);
        console.log('it works');
    };
    addImage = async (image) => {
        await fetch('https://localhost:44385/api/users/CreateImage',
            {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + sessionStorage.tokenKey
                },
                body: this.state.file
            }
        )
    }
    
    handleImageChange(e) {
        e.preventDefault();
        let form = new FormData();
        for (var index = 0; index < e.target.files.length; index++) {
            var element = e.target.files[index];
            form.append('image', element);
        }
        form.append('fileName', "Img");
        this.setState({ file: form });
    };    
    

【讨论】:

  • 非常感谢,它完美运行!这个决定我什至没有想到,虽然我认为我已经尝试了一切。你把我从痛苦中解救了:)
  • 我如何在 .net WebAPI 2.0 中实现这个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 2020-04-08
  • 1970-01-01
  • 2020-03-15
  • 2021-07-07
  • 2021-01-27
  • 2019-03-04
相关资源
最近更新 更多