2016-06-15 111 views
6

我不熟悉azure或rest api或c#,但无论如何,我必须这样做,并且我没有找到一个好的文档来指导我......使用rest api将文件上传到网络应用的Azure文件存储

所以这个Web应用程序,目前一个WebForm,没有MVC ......这是怎么回事Azure平台上托管,

这个Web应用程序的主要功能是用户上传文件到Azure的文件存储。

这些文件可能是PDF或MP3等,不是简单的文本或数据流或数据输入。

我被告知要使用Azure REST API来上传文件,但我实际上并不熟悉它,无法在线找到好的示例或教程或视频。目前来自微软的文件看起来像是??????对我来说。

目前我只是上传到本地文件夹,所以代码如下所示: FileUpload1.PostedFile.SaveAs(Server.MapPath("fileupload\\" + FileUpload1.FileName)); in C#;

我从哪里开始?我想我应该添加一个StorageConnectionString,它看起来像我已经拥有的DefaultEndpointsProtocol=https;AccountName=xxx;AccountKey=yyy

然后,我应该写一些代码,如'后'在C#中?这部分我真的不知道。这是一个愚蠢的问题吗?

我真是一个初学者,我要感谢所有帮助,谢谢你们(T,T)

回答

13

天青提供您可以用它来上传的NuGet库,并做其他的“文件管理”类型的Azure文件存储上的活动。

库被称为: WindowsAzure.Storage

这里有得到这个正在进行的基础:这里

//Connect to Azure 
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); 

// Create a reference to the file client. 
CloudFileClient = storageAccount.CreateCloudFileClient();  

// Create a reference to the Azure path 
CloudFileDirectory cloudFileDirectory = GetCloudFileShare().GetRootDirectoryReference().GetDirectoryReference(path); 

//Create a reference to the filename that you will be uploading 
CloudFile cloudFile = cloudSubDirectory.GetFileReference(fileName); 

//Open a stream from a local file. 
Stream fileStream= File.OpenRead(localfile); 

//Upload the file to Azure. 
await cloudFile.UploadFromStreamAsync(fileStream); 
fileStream.Dispose(); 

更多链接和信息(注意滚动一种公平的方式下进行的样品):https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-files/

+0

哦,我在哭,这很有帮助,谢谢!拯救我的一天。解决了大部分问题! – AprilX

+0

正因为如此,我们使用“等待”?有必要吗?当我使用它时,错误表示“等待操作符只能在Async方法中使用”,当我向我的“protected void Button1_Click”(这是按钮点击上传文件)添加异步时,将其更改为“protected async void” ,另一个错误将显示为“此时异步操作无法启动”...... 我感到羞愧,我不明白这么多东西(T。T) – AprilX

+1

'UploadFromStreamAsync'是一个异步方法。所以你需要把它放在一个带异步''static async void UploadFile()''的方法中,或者使用Wait()函数使其同步。 'cloudFile.UploadFromStreamAsync(FILESTREAM).Wait();'。祝你好运。 –

3

这段代码是基于我从上面加里霍兰得到的答案。我希望其他人从中受益。我不善于编程,希望代码看起来不错。

if (FileUpload1.HasFile) 
    { 
     //Connect to Azure 
     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); 

     // Create a reference to the file client. 
     CloudFileClient fileClient = storageAccount.CreateCloudFileClient(); 

     // Get a reference to the file share we created previously. 
     CloudFileShare share = fileClient.GetShareReference("yourfilesharename"); 

     if (share.Exists()) 
     { 


      // Generate a SAS for a file in the share 
      CloudFileDirectory rootDir = share.GetRootDirectoryReference(); 
      CloudFileDirectory sampleDir = rootDir.GetDirectoryReference("folderthatyouuploadto"); 
      CloudFile file = sampleDir.GetFileReference(FileUpload1.FileName); 

      Stream fileStream = FileUpload1.PostedFile.InputStream; 

      file.UploadFromStream(fileStream); 
      fileStream.Dispose(); 


     } 
    } 
相关问题