2013-09-26 169 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方法。

相关问题