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.
당신은 당신이'Server' 객체에 접근 할 수 없다는 것을 의미합니까? – AthibaN
컨트롤러 외부의 실제 경로에 가상 경로를 매핑해야하는 경우 ['HostingEnvironment.MapPath'] (http://msdn.microsoft.com/en-us/library/system.web.hosting)를 사용할 수 있습니다. 호스트 환경. 맵퍼 % 28v = 대 90 % 29.ASPX) 메소드. –
'HttpContext.Current.Server'? –