2013-09-26 165 views
1

我已經看到很多在使用MVC上傳文件的工作examples將文件上傳到文件系統

不過,我想跟進不同的方法,從而,我想一點抽象如下:

我想介紹的FileService,並注入該控制器的依賴。讓服務上傳文件並返回一個UploadedFile對象。

我現在遇到的問題是上傳到文件系統或應用程序根目錄中的正確位置/目錄。

在控制器中,我可以訪問Server對象,我可以稱其爲Server.MapPath,它具有魔力,下面我無法訪問該對象,因爲它不是Controller

如何上傳到文件系統或項目根目錄下的任何位置?

public class FileService : IFileService 
{ 
    private const string UploadBase = "/Files"; 

    public File UploadFile(HttpPostedFileBase file) 
    { 
     if (file != null) 
     { 
      string folder = DateTime.Today.Month + "-" + DateTime.Today.Year; 

      string finalFolder = Path.Combine(UploadBase, folder); 

      if (!Directory.Exists(finalFolder)) 
      { 
       return Directory.CreateDirectory(finalFolder); 
      } 


      var filename = UploadFile(file, directoryInfo.Name + "/"); 


      var newFile = new File { ContentType = file.ContentType, FilePath = filename, Filename = file.FileName }; 

      return newFile; 

     } 

     return null; 
    } 

錯誤是: The SaveAs method is configured to require a rooted path, and the path '9-2013/037a9ddf-7ffe-4131-b223-c4b5435d0fed.JPG' is not rooted.

+0

你的意思是你不能訪問'服務器'對象? – AthibaN

+1

如果您需要將虛擬路徑映射到控制器外部的物理路徑,可以使用['HostingEnvironment.MapPath'](http://msdn.microsoft.com/zh-cn/library/system.web.hosting。 hostingenvironment.mappath%28v = vs.90%29.ASPX)方法。 –

+0

'HttpContext.Current.Server'? –

回答

1

再說明什麼評論指出:

如果您想對物理路徑的虛擬路徑映射控制器以外,可以隨時使用HostingEnvironment.MapPath方法。

相關問題