upload media to azure blob storage using asp.net web api 2

985 Views Asked by At

I'm developing rest web api that uploads images to my azure blob, I used one of the online tutorial and got this code

 public class DocumentsController : ApiController
{
    private const string CONTAINER = "documents";

    // POST api/<controller>
    public async Task<HttpResponseMessage> Post()
    {
        var context = new StorageContext();

        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        // Get and create the container
        var blobContainer = context.BlobClient.GetContainerReference(CONTAINER);
        blobContainer.CreateIfNotExists();

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

        try
        {
            // Read the form data and return an async task.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names for uploaded files.
            foreach (var fileData in provider.FileData)
            {
                var filename = fileData.LocalFileName;
                var blob = blobContainer.GetBlockBlobReference(filename);

                using (var filestream = File.OpenRead(fileData.LocalFileName))
                {
                    blob.UploadFromStream(filestream);
                }
                File.Delete(fileData.LocalFileName);
            }

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

it is uploading the image in my account blob container but when i open azure storage manager and access the container i get wrong format as below picture describes

enter image description here

can u see the content-type ? I'm not able open this path in explorer any help would be appreciated

1

There are 1 best solutions below

8
On BEST ANSWER

Is your "filename" from code below have extension included when you debuging (like .jpg, .png)? For example "image.jpg"

var blob = blobContainer.GetBlockBlobReference(filename);

Also "fileData.LocalFileName" from code below need to have file extension

using (var filestream = File.OpenRead(fileData.LocalFileName))

It doesn't have extension and for this reason you have such issue