gpt4 book ai didi

angularjs - Dotnet Core 中的多部分 MemoryStream

转载 作者:行者123 更新时间:2023-12-04 03:06:01 25 4
gpt4 key购买 nike

我有一个要迁移到 Dot Net Core 的 .Net 4.5.2 应用程序。此应用程序允许用户上传带有元数据(Angular 客户端)的文件,并且 Api 将处理请求并处理文件。这是执行此操作的现有代码。

接口(interface)

[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<>));
}
}

所以这完全适用于定位框架,但在核心中我在这条线上遇到了一个异常(exception)

.StartNew(() => parts = Request.Content.ReadAsMultipartAsync(streamProvider).Result.Contents,



异常(exception)

'HttpRequest' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)



我需要什么来确保我可以获得这个文件和元数据? Core 中有没有办法从 HttpRequest 获取 HttpContent

最佳答案

Asp.Net Core 支持内置的多部分文件上传。当您拥有 List<IFormFile> 时,模型绑定(bind)组件将使其可用。范围。
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});
}

关于angularjs - Dotnet Core 中的多部分 MemoryStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44314129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com