Dot Net Core中的MultipartMemoryStream

时间:2017-06-01 17:52:52

标签: angularjs .net-core multipartform-data

我有一个.Net 4.5.2应用程序,我正在转向Dot Net Core。此应用程序允许用户上传带有元数据(Angular Client Side)的文件,Api将处理请求并处理文件。这是现有的代码。

阿比

[HttpPost]
[Route("AskQuestions")]
public void ProvideClarifications(int id)
{
  var user = base.GetUserLookup();
  if (user != null)
  {
    var streamProvider = new MultiPartStreamProvider();
    IEnumerable<HttpContent> parts = null;
    Task.Factory
        .StartNew(() => parts = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,
            CancellationToken.None,
            TaskCreationOptions.LongRunning,
            TaskScheduler.Default)
        .Wait();

        // do some stuff with streamProvider.FormData
  }
}

处理文件和元数据的提供商

public class MultiPartStreamProvider : MultipartMemoryStreamProvider
{
    private string _originalFileName = string.Empty;
    public Dictionary<string, object> FormData { get; set; }

    public byte[] ByteStream { get; set; }

    public string FileName
    {
        get
        {
            return _originalFileName.Replace("\"", "");
        }
    }
    public MultiPartStreamProvider()
    {
        this.FormData = new Dictionary<string, object>();
    }
    public override Task ExecutePostProcessingAsync()
    {
        foreach (var content in Contents)
        {
            var contentDispo = content.Headers.ContentDisposition;
            var name = UnquoteToken(contentDispo.Name);

            if (name.Contains("file"))
            {
                _originalFileName = UnquoteToken(contentDispo.FileName);
                this.ByteStream = content.ReadAsByteArrayAsync().Result;
            }
            else
            {
                var val = content.ReadAsStringAsync().Result;
                this.FormData.Add(name, val);
            }
        }
        return base.ExecutePostProcessingAsync();
    }
    private static string UnquoteToken(string token)
    {
        if (String.IsNullOrWhiteSpace(token))
        {
            return token;
        }

        if (token.StartsWith("\"", StringComparison.Ordinal) && token.EndsWith("\"", StringComparison.Ordinal) && token.Length > 1)
        {
            return token.Substring(1, token.Length - 2);
        }

        return token;
    }
}
static class FormDataExtensions {
    public static Object GetObject(this Dictionary<string, object> dict, Type type)
    {
        var obj = Activator.CreateInstance(type);

        foreach (var kv in dict)
        {
            var prop = type.GetProperty(kv.Key);
            if (prop == null) continue;

            object value = kv.Value;
            var targetType = IsNullableType(prop.PropertyType) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType;

            if (value is Dictionary<string, object>)
            {
                value = GetObject((Dictionary<string, object>)value, prop.PropertyType); // <= This line                   
            }
            value = Convert.ChangeType(value, targetType);
            prop.SetValue(obj, value, null);
        }
        return obj;
    }
    public static T GetObject<T>(this Dictionary<string, object> dict)
    {
        return (T)GetObject(dict, typeof(T));
    }
    private static bool IsNullableType(Type type)
    {
        return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
    }
}

所以这对目标框架起作用非常好,但在Core中我在这一行得到了一个例外

  

.StartNew(()=&gt; parts = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,

异常

  

'HttpRequest'不包含'Content'的定义,并且没有扩展方法'Content'可以找到接受'HttpRequest'类型的第一个参数(你是否缺少using指令或汇编引用?)

我需要什么才能确保获得此文件和元数据?在Core中有没有办法从HttpRequest获取HttpContent

1 个答案:

答案 0 :(得分:2)

Asp.Net Core支持内置的多部分文件上传。模型绑定组件将在您拥有List<IFormFile>参数时使其可用。

有关详细信息,请参阅docs on file uploads,以下是处理分段上传的相关示例:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}