如何将图像从React上传到ASP.NET Core Web API? [英] How to upload image from React to ASP.NET Core Web API?
问题描述
我在mt服务器端具有Web API控制器
I have Web API controller in mt server side
[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在哪里
Where ImageDTO is
public class ImageDTO
{
public string FileName { get; set; }
public IFormFile Image { get; set; }
}
和类似Image.cs
and Image.cs like this
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客户端上处理和发送图像的东西:
And this is what I using for handling and sending image on React client:
<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>
将文件处理为状态的功能
function for handling file into state
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');}
addImge函数:
addImge function:
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服务器发送图像的可行示例.我需要你们的帮助!
But when it`s sending request on server it return Error 400, which means "Bad Request". So I think it is may be wrong type of data sent or something like that. Maybe someone sees a mistake or something that can be fixed. Or someone could show a working example of sending images from React to Web Api server. I need your help guys!
推荐答案
要上传,请注意以下几点:
For uploading, you need to pay attention to points below:
- 您需要将
formdata
与FromForm
一起使用 - formdata中的字段应与模型字段相对应.
步骤:
-
更改控制器动作.
Change the Controller action.
public void CreateImage([FromForm] ImageDTO img)
{
}
客户代码:
Client Code:
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 });
};
这篇关于如何将图像从React上传到ASP.NET Core Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!