How to get stream for Multipart file in webapi upload?

I need to upload a file using Stream (Azure Blobstorage), and just can't find out how to get the stream from the object itself. See code below.

I am new to WebAPI and have used some examples. I get files and filedata, but this is not the right type for my methods to load it. So I need to get or convert it to a regular Stream, which seems a bit complicated at the moment :)

I know that I need to use it somehow ReadAsStreamAsync().Result, but it crashes in the foreach loop since I get two providers. Content (the first seems correct, the second does not).

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

, ( , MultipartStreamProvider ). , ... .:( ( , MultipartFileStreamProvider, MultipartFormDataStreamProvider MultipartStreamProvider ).

; -API .

+3

All Articles