2013-03-17 136 views
0

我一直在嘗試上傳文件到Azure存儲容器。 當我在本地運行我的Web應用程序,如果文件是在網站我得到一個錯誤windows azure上傳文件路徑錯誤:'找不到文件...'

Could not find file 'C:\Program Files (x86)\IIS Express\test.txt'. 

如果我副本文件到Web應用程序根目錄,它工作正常。

運行web應用程序我得到一個錯誤

Could not find file 'D:\Windows\system32\test.txt'. 

我無法從HttpPostedFileBase對象得到完整的本地文件路徑

代碼

private string UploadFile(HttpPostedFileBase file, string folder) 
    { 
     try 
     { 
      var date = DateTime.UtcNow.ToString("yyyyMMdd-hhmmss-"); 
      var fileName = Path.GetFileName(file.FileName); 

      CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=test;AccountKey=asdfasfasdasdf"); 
      CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 
      CloudBlobContainer container = blobClient.GetContainerReference(folder); 
      bool b = container.CreateIfNotExists(); 

      CloudBlockBlob blockBlob = container.GetBlockBlobReference(date + fileName); 
      blockBlob.Properties.ContentType = file.ContentType; 

      using (var fileStream = System.IO.File.OpenRead(fileName)) 
      { 
       blockBlob.UploadFromStream(fileStream); 
      } 
      return blockBlob.Uri.AbsoluteUri; 

     } 
     catch (Exception ex) 
     { 
      return ex.Message; 
     } 

回答

2

HttpPostedFileBase manual是這樣說的;

FileName         Gets the fully qualified name of the file on the client.

也就是說,文件名不是可以在服務器上打開的文件名。

我認爲你真正想要做的是使用InputStream property;

blockBlob.Properties.ContentType = file.ContentType; 

blockBlob.UploadFromStream(file.InputStream); // Upload from InputStream 
return blockBlob.Uri.AbsoluteUri; 
+0

感謝Joachim。它解決了這個問題。 – user2178726 2013-03-17 23:56:15

0

非常感謝:Joachim Isaksson(上圖)我昨天花了整整一天的時間與這一行代碼作鬥爭。我已經投了你的答案,但我想我會添加你的解決方案的副本,它位於我自己的代碼中:

public async Task<ActionResult> UploadAsync() 
{ 
    try 
    { 
     HttpFileCollectionBase files = Request.Files; 
     int fileCount = files.Count; 

     if (fileCount > 0) 
     { 
      for (int i = 0; i < fileCount; i++) 
      { 
       CloudBlockBlob blob = blobContainer.GetBlockBlobReference(GetRandomBlobName(files[i].FileName)); 

       blob.Properties.ContentType = files[i].ContentType; 
       blob.UploadFromStream(files[i].InputStream); 

       // the above 2 lines replace the following line from the downloaded example project: 
       //await blob.UploadFromFileAsync(Path.GetFullPath(files[i].FileName), FileMode.Open); 
      } 
     } 
     return RedirectToAction("Index"); 
    } 
}