2013-09-26 4 views
1

MVC를 사용하여 파일을 업로드 할 때 많은 작업을 보았습니다. examples. 나는 FileService을 소개하고 종속성과 같은 컨트롤러에이를 주입 할파일 시스템에 파일 업로드

:

는 그러나, 나는 다음과 같이 내가 약간의 추상화를 원하는되도록 다른 접근 방식을 따르십시오. 서비스가 파일을 업로드하고 나에게 UploadedFile 객체를 돌려 보자.

지금 문제는 파일 시스템이나 응용 프로그램 루트의 올바른 위치/디렉토리에 업로드하는 것입니다.

컨트롤러에서 나는 Server.MapPath이라고 부를 수있는 Server 개체에 액세스 할 수 있으며, 그 개체는 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

당신은 당신이'Server' 객체에 접근 할 수 없다는 것을 의미합니까? – AthibaN

+1

컨트롤러 외부의 실제 경로에 가상 경로를 매핑해야하는 경우 ['HostingEnvironment.MapPath'] (http://msdn.microsoft.com/en-us/library/system.web.hosting)를 사용할 수 있습니다. 호스트 환경. 맵퍼 % 28v = 대 90 % 29.ASPX) 메소드. –

+0

'HttpContext.Current.Server'? –

답변

1

다시 진술 어떤 의견에서 언급되었다 :

당신이 컨트롤러 외부의 실제 경로에 가상 경로를 매핑하려면, 당신은 항상 할 수 HostingEnvironment.MapPath 방법을 사용하십시오.

관련 문제