我目前正在开发一个c#web API。对于一个特定的调用,我需要使用ajax调用向API发送2个图像,以便API可以将它们保存为数据库中的varbinary(max)。
- 如何从
HttpContent
对象中提取Image
或byte[]
- 我该怎么做两次?每个图像一次
-
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;
}
HttpContent
有一个Async方法,它返回ByteArray,即(ByteArray的任务)
Byte[] byteArray = await Content.ReadAsByteArrayAsync();
您可以同步运行方法
Byte[] byteArray = Content.ReadAsByteArrayAsync().Result;
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);
您可以使用HttpContent.ReadAsByteArrayAsync
:
byte[] bytes = await response.Content.ReadAsByteArrayAsync();
或者,您可以使用HttpContent.ReadAsStreamAsync
读取内容,并从中提取到byte[]
:
var stream = await response.Content.ReadAsStreamAsync();
using (var memoryStream = new MemoryStream())
{
await stream.CopyToAsync(memoryStream);
return memoryStream.ToArray();
}
请查看ByteArrayContent class公开的CopyToAsync(Stream,TransportContext)方法。[msdn链接]