0

I am trying to send data [User ID, File] from UWP to WebAPI2. From WebApi2, I want to create a container in Azure Storage [container name = user ID]. The code is as follows. The first part is the client side [UWP].

foreach (StorageFile file in files)
        {

            filesListView.Items.Add(file.DisplayName);
            IInputStream inputStream = await file.OpenAsync(FileAccessMode.Read);
            HttpMultipartFormDataContent multipartContent = new HttpMultipartFormDataContent();


            //if (i == false)
            //{
                multipartContent.Add(new HttpStringContent(txtbox.Text), "myText");
                i = true;
           // }


            multipartContent.Add(new HttpStreamContent(inputStream), "myFile", file.Name);

            HttpClient client = new HttpClient();
            Uri uri = new Uri("http://localhost:35095/api/upload");
            HttpResponseMessage response = await client.PostAsync(uri,multipartContent);

        }

The code below represents the WebAPI2 code to upload files in Azure Blob:

namespace DemoAzureStorage.Controllers

{ [RoutePrefix("api/upload")] public class UploadController : ApiController {

    [HttpPost, Route("")]
    public async Task<object>  UploadFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        CloudBlobContainer imagesContainer = null;
        string Container;
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);


        try
        {
            await Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((tsk) =>
             {
                 MultipartMemoryStreamProvider prvdr = tsk.Result;
                 var accountName = ConfigurationManager.AppSettings["storage:account:name"];
                 var accountKey = ConfigurationManager.AppSettings["storage:account:key"];
                 var storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
                 CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

                 foreach (HttpContent ctnt in prvdr.Contents)
                 {
                     // You would get hold of the inner memory stream here
                     Stream stream = ctnt.ReadAsStreamAsync().Result;

                     var type1 = ctnt.GetType();




                     if (ctnt.Headers.ContentDisposition.Name == "\"myFile\"")
                     {

                         var filename = ctnt.Headers.ContentDisposition.FileName.Trim();

                         var a = filename;

                         CloudBlockBlob blob = imagesContainer.GetBlockBlobReference(filename);

                         if (ctnt.Headers.ContentType != null)
                         {
                             // Set appropriate content type for your uploaded file
                             blob.Properties.ContentType = ctnt.Headers.ContentType.MediaType;
                         }

                         //  this.FileData.Add(new MultipartFileData(ctnt.Headers, blob.Name));

                           StreamReader rdr = new StreamReader(stream);

                         var a1 = rdr;


                         blob.UploadFromStream(stream);

                     }

                     else
                     {
                         string aaa = ctnt.Headers.ContentDisposition.ToString();

                         StreamReader rdr = new StreamReader(stream);

                         Container = rdr.ReadLine();
                         string z = Container;

                         imagesContainer = blobClient.GetContainerReference(z);
                         imagesContainer.CreateIfNotExists();


                         while (!rdr.EndOfStream)
                         {
                             // Console.WriteLine(rdr.ReadLine());
                             Trace.WriteLine(rdr.ReadLine());
                         }


                     }
                 }
             });

            return Request.CreateResponse(HttpStatusCode.OK);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

}

}

In this above WebApi2 code, the Azure storage container is being created but when I call the following method, the blob is created but with "0 byte size" i.e, no data/ content is being passed to blob rather only a blob is created with respective file name:

  blob.UploadFromStream(stream);

Need help to pass the data of the text file to the blob as it is. Any help/ suggestions would be highly appreciated. Thanks :)

N.B: I'm a newbie :)

  • Please try to reset the stream's position to `0`. Try by adding following line of code: `stream.Position = 0;` after this line: `Stream stream = ctnt.ReadAsStreamAsync().Result;`. HTH. – Gaurav Mantri Sep 05 '16 at 09:41
  • @GauravMantri: Thanks for replying. The text file is getting created using your method too, but the only issue is that the file is getting saved as ".txt_" file instead of simply ".txt". The last character "_" after txt is causing trouble. As it can't be opened later. – crakx freeman Sep 05 '16 at 09:59
  • I'm confused now :). Earlier you mentioned that the file is of zero bytes. Is that now fixed? If I understand correctly, you're having a new issue now with the name of the file. Correct? – Gaurav Mantri Sep 05 '16 at 10:05
  • Yes sir, thank you, the file size is no more zero byte. That is fixed now. But it is not getting opened now after trying to download it from the Azure storage, which I realized just now. As the filename is getting saved as .txt_ – crakx freeman Sep 05 '16 at 10:18
  • Issue resolved by adding following line: filename.Replace("\"", ""); – crakx freeman Sep 05 '16 at 11:01

0 Answers0