我需要使用Stream(Azure Blobstorage)上传文件,而无法找到如何从对象本身获取流。请参阅下面的代码。
我是WebAPI的新手,并使用了一些示例。我正在获取文件和filedata,但我的方法上传它并不正确。因此,我需要将其转换或转换为普通的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);
}
答案 0 :(得分:3)
这与几个月前的困境相同(在MultipartStreamProvider
接管之前捕获上传流并自动神奇地将流保存到文件中)。建议是继承该类并覆盖方法......但这在我的情况下不起作用。 :((我希望将MultipartFileStreamProvider
和MultipartFormDataStreamProvider
的功能集合到一个MultipartStreamProvider中,而不使用自动保存部分。)
这可能会有所帮助;来自同一开发者的here's one written by one of the Web API developers和this。
答案 1 :(得分:1)
您好,我只是想发布我的答案,因此,如果有人遇到相同的问题,他们可以在这里自己找到解决方案。
这里
MultipartMemoryStreamProvider stream = await this.Request.Content.ReadAsMultipartAsync();
foreach (var st in stream.Contents)
{
var fileBytes = await st.ReadAsByteArrayAsync();
string base64 = Convert.ToBase64String(fileBytes);
var contentHeader = st.Headers;
string filename = contentHeader.ContentDisposition.FileName.Replace("\"", "");
string filetype = contentHeader.ContentType.MediaType;
}
我使用了MultipartMemoryStreamProvider,并从内容的标题中获取了文件名和文件类型之类的所有详细信息。 希望这对某人有帮助。