2011-02-14 22 views
5

我想上傳一個文件,並將其發送到服務層保存,但我不斷找到有關如何控制器獲取HTTPPostedFileBase並將其直接保存在控制器。我的服務層對web dll沒有依賴性,因此我是否需要將我的對象讀入內存流/字節?我應該如何去這個任何指針是極大的讚賞...上傳文件併發送到服務層即ie#c#類庫

注:文件可以通過PDF,Word,以便我可能還需要檢查的內容類型(可能內域名服務層...

代碼:

public ActionResult UploadFile(string filename, HttpPostedFileBase thefile) 
{ 
//what do I do here...? 


} 

編輯:

public interface ISomethingService  
{ 
    void AddFileToDisk(string loggedonuserid, int fileid, UploadedFile newupload);  
} 
    public class UploadedFile 
    { 
     public string Filename { get; set; } 
     public Stream TheFile { get; set; } 
     public string ContentType { get; set; } 
    } 

public class SomethingService : ISomethingService  
{ 
    public AddFileToDisk(string loggedonuserid, int fileid, UploadedFile newupload) 
    { 
    var path = @"c:\somewhere"; 
    //if image 
    Image _image = Image.FromStream(file); 
    _image.Save(path); 
    //not sure how to save files as this is something I am trying to find out... 
    } 
} 
+0

你能告訴我們你的服務層是怎樣的嗎? – 2011-02-14 11:27:08

回答

10

您可以使用貼FIL的InputStream財產E要閱讀的內容作爲字節數組,並將其發送給服務層與其他信息,如ContentTypeFileName您的服務層可能需要沿着:

public ActionResult UploadFile(string filename, HttpPostedFileBase thefile) 
{ 
    if (thefile != null && thefile.ContentLength > 0) 
    { 
     byte[] buffer = new byte[thefile.ContentLength]; 
     thefile.InputStream.Read(buffer, 0, buffer.Length); 
     _service.SomeMethod(buffer, thefile.ContentType, thefile.FileName); 
    } 
    ... 
} 
1

你能不能在業務層上創建的方法接受Stream作爲參數並將theFile.InputStream傳遞給它?流不需要任何與Web相關的依賴關係,並且避免通過複製其他數據結構中的數據來消耗內存來複制內存。

相關問題