Upload a Single File to Blob Storage Azure

前端 未结 3 789
你的背包
你的背包 2020-12-05 04:35

How can I to Upload a file with C# ? I need to upload a file from a dialogWindow.

3条回答
  •  广开言路
    2020-12-05 05:21

    Here is the complete method.

     [HttpPost]
            public ActionResult Index(Doctor doct, HttpPostedFileBase photo)
            {
    
                try
                {
                    if (photo != null && photo.ContentLength > 0)
                    {
                        // extract only the fielname
                        var fileName = Path.GetFileName(photo.FileName);
                        doct.Image = fileName.ToString();
    
                        CloudStorageAccount cloudStorageAccount = DoctorController.GetConnectionString();
                        CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                        CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
    
    
                        string imageName = Guid.NewGuid().ToString() + "-" +Path.GetExtension(photo.FileName); 
    
                        CloudBlockBlob BlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
    
                        BlockBlob.Properties.ContentType = photo.ContentType;
                        BlockBlob.UploadFromStreamAsync(photo.InputStream);
                        string imageFullPath = BlockBlob.Uri.ToString();
    
                        var memoryStream = new MemoryStream();
    
    
                        photo.InputStream.CopyTo(memoryStream);
                        memoryStream.ToArray();
    
    
    
                        memoryStream.Seek(0, SeekOrigin.Begin);
                        using (var fs = photo.InputStream)
                        {
                            BlockBlob.UploadFromStreamAsync(memoryStream);
                        }
    
                    }
                }
                catch (Exception ex)
                {
    
                }
    
    
                return View();
            }
    

    where the getconnectionstring method is this.

     static string accountname = ConfigurationManager.AppSettings["accountName"];
          static  string key = ConfigurationManager.AppSettings["key"];
    
    
                public static CloudStorageAccount GetConnectionString()
                {
    
                    string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountname, key);
                    return CloudStorageAccount.Parse(connectionString);
                }
    

提交回复
热议问题