我目前正在开发一个c#web API。对于特定的调用,我需要使用对API的ajax调用发送2个图像,以便API可以将它们保存为数据库中的varbinary(max)。
Image
对象中提取byte[]
或HttpContent
?-
var authToken = $("#AuthToken").val();
var formData = new FormData($('form')[0]);
debugger;
$.ajax({
url: "/api/obj/Create/",
headers: { "Authorization-Token": authToken },
type: 'POST',
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
data: formData,
cache: false,
contentType: false,
processData: false
});
-
public async Task<int> Create(HttpContent content)
{
if (!content.IsMimeMultipartContent())
{
throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");
}
return 3;
}
答案 0 :(得分:17)
FileReader
有一个返回ByteArray的异步方法,即(ByteArray的任务)
HttpContent
您可以同步运行该方法
Byte[] byteArray = await Content.ReadAsByteArrayAsync();
答案 1 :(得分:2)
if (!content.IsMimeMultipartContent())
{
throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");
}
var uploadPath = **whatever**;
if (!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);
}
var provider = new MultipartFormDataStreamProvider(uploadPath);
await content.ReadAsMultipartAsync(provider);
return File.ReadAllBytes(provider.FileData[0].LocalFileName);
答案 2 :(得分:0)
请查看ByteArrayContent类公开的CopyToAsync(Stream,TransportContext)方法。 [msdn link]
答案 3 :(得分:0)
您可以使用HttpContent.ReadAsByteArrayAsync
:
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
或者,您可以使用HttpContent.ReadAsStreamAsync
阅读内容并从那里摘录到byte[]
:
var stream = response.Content.ReadAsStreamAsync();
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(stream);
return memoryStream.ToArray();
}