你好,
我正在尝试将 javascript blob 图像发送到我在 ASP.NET Core 中的 Controller 方法,但它没有发送到我的 Controller 。
我有一张来自 Canvas 的图像,它是 dataUri
能够将其转换为 javascript blob,我正在使用此代码:
dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
// create a view into the buffer
var ia = new Uint8Array(ab);
// set the bytes of the buffer to the correct values
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], { type: mimeString });
return blob;
}
// Then in my save method here are my javascript codes:
const fileImage = this.dataURItoBlob(myDataUriImage);
axios.post(`Info/Create`, fileImage , {
headers: {
"Content-Type": "multipart/form-data"
}
})
这是我简单的 ASP.NET Core Controller 方法
public async Task<IActionResult> Create([FromBody]IFormFile fileImage)
{
...
}
有什么帮助吗?
最佳答案
要通过 AJAX 发布文件,您需要 FormData
JS 类。
var formData = new FormData();
formData.append('fileImage', fileImage);
然后,您提交 formData
而不是 fileImage
作为您帖子中的数据。
请记住,通过 AJAX 提交文件需要 HTML5,因此需要现代浏览器。这似乎不是问题,因为您已经大量使用文件 API,它也是 HTML5。请注意,这些都不适用于 IE10 或更低版本。
此外,这仅适用于您在此处使用的 multipart/form-data
mime 类型的请求。作为引用,如果要发送 JSON,文件需要编码为 Base64 字符串并作为 JSON 对象的另一个成员发送。在服务器端,您需要绑定(bind)到 byte[]
而不是 IFormFile
。
关于javascript - 将 javascript 图像 blob 保存到 ASP.NET Core Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51203256/