将 javascript 图像 blob 保存到 ASP.NET Core 控制器

jso*_*PPD 10 javascript c# asp.net-core axios asp.net-core-2.0

再会,

我正在尝试将 javascript blob 图像发送到 ASP.NET Core 中的控制器方法,但它不会发送到我的控制器。

我的画布上有一张图像,它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"
    }
})
Run Code Online (Sandbox Code Playgroud)

这是我的简单 ASP.NET Core 控制器方法

public async Task<IActionResult> Create([FromBody]IFormFile fileImage)
{
 ...
}
Run Code Online (Sandbox Code Playgroud)

有什么帮助吗?

Chr*_*att 2

要通过 AJAX 发布文件,您需要FormDataJS 类。

var formData = new FormData();
formData.append('fileImage', fileImage);
Run Code Online (Sandbox Code Playgroud)

然后,您提交formData而不是fileImage作为帖子中的数据。

请记住,通过 AJAX 提交文件需要 HTML5,因此需要现代浏览器。这似乎不是问题,因为您已经大量使用了 File API(也是 HTML5)。请注意,这些在 IE10 或更低版本中都不起作用。

此外,这仅适用于multipart/form-data您在此处使用的 mime 类型的请求。作为参考,如果要发送 JSON,则需要将文件编码为 Base64 字符串并作为 JSON 对象的另一个成员发送。在服务器端,您需要绑定到而byte[]不是IFormFile.