我需要使用Stream(Azure Blobstorage)上傳文件,並且無法找到如何從對象本身獲取流。見下面的代碼。如何在webapi上傳中獲取Multipart文件的流?
我是新來的的WebAPI,並用一些例子。我正在獲取這些文件和filedata,但是我的方法無法上傳它。因此,我需要得到或轉換成一個正常的流,這似乎有點困難:)
我知道我需要使用ReadAsStreamAsync().Result
以某種方式,但它崩潰在foreach循環,因爲我是得到兩個供應商。內容(第一個似乎是正確的,第二個沒有)。
[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);
}
1.什麼'GetMultipartProvider ()'return?2.我相信你可以從提供者獲得自動保存的文件的文件路徑,並使用通常的'System.IO.File'或'System.IO.FileInfo'類來檢索流 –
這裏是方法:) private MultipartFormDataStreamProvider GetMultipartProvider() var uploadFolder =「〜/ App_Data/Tmp/Fi leUploads「; //你可以把它放到web.config中 var root = HttpContext.Current.Server.MapPath(uploadFolder); Directory.CreateDirectory(root); 返回新的MultipartFormDataStreamProvider(root); } –
我可以從這裏獲取文件嗎?基本上,我不需要將其存儲到磁盤..我只需要流上傳到蔚藍的Blob存儲:) 任何想法? –