2013-03-17 223 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"); 
    } 
} 
相关问题