gpt4 book ai didi

c# - 如何在webapi上传中获取多部分文件的流?

转载 作者:太空狗 更新时间:2023-10-29 23:22:39 25 4
gpt4 key购买 nike

我需要使用流(Azure Blobstorage)上传文件,但不知道如何从对象本身获取流。请参阅下面的代码。

我是 WebAPI 的新手,并且使用过一些示例。我正在获取文件和文件数据,但对于我的上传方法来说,这不是正确的类型。因此,我需要将其获取或转换为普通的 Stream,目前看来有点困难:)

我知道我需要以某种方式使用 ReadAsStreamAsync().Result ,但它在 foreach 循环中崩溃,因为我得到了两个provider.Contents(第一个似乎是正确的,第二个似乎是正确的)不是)。

 [System.Web.Http.HttpPost]
public async Task<HttpResponseMessage> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}

var provider = GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);

// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());

// uploadedFileInfo object will give you some additional stuff like file length,
// creation time, directory name, a few filesystem methods etc..
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);



// Remove this line as well as GetFormData method if you're not
// sending any form data with your upload request
var fileUploadObj = GetFormData<UploadDataModel>(result);

Stream filestream = null;

using (Stream stream = new MemoryStream())
{
foreach (HttpContent content in provider.Contents)
{
BinaryFormatter bFormatter = new BinaryFormatter();
bFormatter.Serialize(stream, content.ReadAsStreamAsync().Result);
stream.Position = 0;
filestream = stream;
}
}

var storage = new StorageServices();
storage.UploadBlob(filestream, originalFileName);**strong text**



private MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = "~/App_Data/Tmp/FileUploads"; // you could put this to web.config
var root = HttpContext.Current.Server.MapPath(uploadFolder);
Directory.CreateDirectory(root);
return new MultipartFormDataStreamProvider(root);
}

最佳答案

这与我几个月前遇到的困境相同(在 MultipartStreamProvider 接管并自动将流保存到文件之前捕获上传流)。建议是继承该类并重写方法......但这对我来说不起作用。 :((我希望将 MultipartFileStreamProviderMultipartFormDataStreamProvider 的功能整合到一个 MultipartStreamProvider 中,而不需要自动保存部分)。

这可能有帮助; here's one written by one of the Web API developers ,和this来自同一开发商。

关于c# - 如何在webapi上传中获取多部分文件的流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24806664/

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