将HttpContent转换为byte []

Jam*_*son 8 c# bytearray stream type-conversion httpcontext

我目前正在研究ac #web API.对于特定的调用,我需要使用对API的ajax调用发送2个图像,以便API可以将它们保存为数据库中的varbinary(max).

  1. 如何从对象中提取Imagebyte[]HttpContent对象中提取?
  2. 我该怎么做两次?一次为每个图像.

-

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
});
Run Code Online (Sandbox Code Playgroud)

-

public async Task<int> Create(HttpContent content)
{
    if (!content.IsMimeMultipartContent())
    {
        throw new UnsupportedMediaTypeException("MIME Multipart Content is not supported");
    }

    return 3;
}
Run Code Online (Sandbox Code Playgroud)

Cle*_*gic 17

HttpContent 有一个Async方法返回ByteArray ie(ByteArray的任务)

 Byte[] byteArray = await Content.ReadAsByteArrayAsync();
Run Code Online (Sandbox Code Playgroud)

您可以同步运行该方法

Byte[] byteArray = Content.ReadAsByteArrayAsync().Result;
Run Code Online (Sandbox Code Playgroud)


Jam*_*son 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);
Run Code Online (Sandbox Code Playgroud)