Isa*_*vin 3 multipartform-data angularjs .net-core
我有一个 .Net 4.5.2 应用程序,我要迁移到 Dot Net Core。此应用程序允许用户上传带有元数据(Angular 客户端)的文件,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
}
}
Run Code Online (Sandbox Code Playgroud)
处理文件和元数据的提供者
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<>));
}
}
Run Code Online (Sandbox Code Playgroud)
所以这完全适用于定位框架,但在 Core 中,我在这条线上得到了一个例外
.StartNew(() => 部分 = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,
例外
“HttpRequest”不包含“Content”的定义,并且找不到接受“HttpRequest”类型的第一个参数的扩展方法“Content”(您是否缺少 using 指令或程序集引用?)
我需要做什么来确保我可以获得这个文件和元数据?Core 中有没有办法从 HttpRequest 中获取 HttpContent
Asp.Net Core 支持内置的多部分文件上传。当您有List<IFormFile>参数时,模型绑定组件将使其可用。
有关更多详细信息,请参阅文件上传文档,以下是处理分段上传的相关示例:
Run Code Online (Sandbox Code Playgroud)[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}); }
| 归档时间: |
|
| 查看次数: |
3258 次 |
| 最近记录: |