How do I upload a file to Azure blob storage from a MVC view

醉酒当歌 提交于 2019-12-04 07:46:45
Perry Skountrianos - MSFT

One way to call your UploadTestFile() function from an MVC View is by using the Html.BeginForm() method. I am including an example below:

@using (Html.BeginForm("UploadTestFile", "INSERT_YOUR_CONTROLLER_NAME_HERE", FormMethod.Post, new { enctype = "multipart/form-data" })) {
    <span>
        <input type="file" name="myFile" multiple /> <br>
        <input type="submit" value="Upload" />
    </span>

}

Also, a couple of suggestions on your code:

  1. UploadFileToBlobStorage(): The code checks for container existence and setting permissions on every request. I would recommend separating the container.CreateIfNotExists() and container.SetPermissions(…) logic into a separate initialization function that needs to be executed only once on first deployment.

  2. UploadFileToBlobStorage(): It looks like the code will try to upload the localFileName from the VM file system and not the multi-part form data. One approach would be to use the HttpFileCollectionBase class and the Controller.Request property. Example below:

    public void UploadFileToBlobStorage(
        string containerName, 
        string blockBlogName, 
        HttpFileCollectionBase files) 
    {
    
        // .....
    
        // Use this:
        blockBlob.UploadFromStream(files[0].InputStream); 
    
        /* uploading the first file: 
           you can enumerate thru the files collection 
           if you are uploading multiple files */
    
        /* Instead of this: 
           Create or overwrite the "myblob" blob with contents 
           from a local file. */
        using (var fileStream = System.IO.File.OpenRead(fileName)) 
        {
            blockBlob.UploadFromStream(fileStream);
        }
    }
    
    [HttpPost]
    public void UploadTestFile() 
    {
        string containerName = "TestContainer";
        string blockBlogName = "Test.txt";
        AzureService azureService = new AzureService();
    
        // Notice the Request.Files instead of localFileName
        azureService.UploadFileToBlobStorage(
              containerName, blockBlogName, Request.Files);
    }
    

Please let me know if that works on your end.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!