javascript - 如何将文件图像转换为字节 [] ReactJS?
问题描述
我想将图像发送到 api 端点和端点接受字节 [] 我该如何处理。我的代码是:点击上传按钮时的 ReactJS 函数:
let onClickHandler = () => {
let data = new FormData()
data.append('file', image);
axios.post("/Contact/ContactForm/", {
AttachedImage: data
}, {
headers: {
'Content-Type': 'multipart/form-data',
'X-Requested-With': 'XMLHttpRequest',
}
// receive two parameter endpoint url ,form data
})
.then(res => { // then print response status
console.log('binary Response......',res.statusText)
});
}
和我的端点控制器方法:
[HttpPost]
public async Task<IActionResult> ContactForm([FromBody] Contact model)
{
try
{
model.CreationDate = DateTime.Now;
await _contact.ContactForm(model);
return Ok("Submitted Successfully");
}
catch (Exception ex) { return this.BadRequest("Not Submitted Successfully" + ex.ToString()); }
}
最后是 Model.cs 类
public byte[] AttachedImage { set; get; }
解决方案
想将图像发送到 api 端点和端点接受字节 [] 我该如何处理。
请注意,默认模型绑定器无法处理将设置为的字节数组null
。
要上传图像文件并将数据绑定到模型类的字节数组属性,您可以尝试以下解决方案:
解决方案1 - 将所选图像文件转换为base64编码字符串,并使用aByteArrayModelBinder
将其转换为字节数组。
public class Contact
{
[ModelBinder(BinderType = typeof(ByteArrayModelBinder))]
public byte[] AttachedImage { set; get; }
public DateTime CreationDate { set; get; }
//...
//other properties
//...
}
测试数据
{
"attachedImage": "iVBORw0KGgoAAAANSUhEUgAAAMsAAA.....",
"creationDate": "2021-08-21T15:12:05"
}
测试结果
解决方案 2 - 实现并使用如下所示的自定义模型绑定器将选定的图像文件绑定到字节数组。
public class ImageToByteArrayModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
// ...
// implement it based on your actual requirement
// code logic here
// ...
if (bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"]?.Length > 0)
{
var fileBytes = new byte[bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].Length];
using (var ms = new MemoryStream())
{
bindingContext.ActionContext.HttpContext.Request.Form.Files["AttachedImage"].CopyTo(ms);
fileBytes = ms.ToArray();
}
bindingContext.Result = ModelBindingResult.Success(fileBytes);
}
return Task.CompletedTask;
}
}
测试结果
推荐阅读
- java - 静态方法中的同步块将获取类级别锁或对象级别锁
- sql - Postgres - 在返回多行后选择一行
- shell - 使用 pod 获取 kubernetes 节点上的设备挂载信息
- python - 使用 SequenceMatcher 在 python 中使用 numba 加速
- java - GCP Spanner 中的动态查询生成器
- javascript - 如何自定义 Intl.DateTimeFormat 日期?
- xml - 如何读取具有多个元素的 xml 文件并使用进度 4gl dom 写入临时表?
- angular - Openlayers 地图不使用全宽
- exoplayer - Android App 可以像 Tiktok 一样即时播放视频
- django - 向用户请求 Django POST API 中的某些元素