我在 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 = 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 服务器的工作示例。我需要你们的帮助!