2016-04-06 15 views
0

我在Asp.NET MVC 4中有一個應用程序,其中用戶上傳要處理的文件2次。我第一次找到頭和行數,第二次(取決於用戶的輸入),我將該文件映射到一個對象(這是一個.csv文件,我需要解析頭文件)。我有這樣的事情(方法是通過AJAX消耗):如何在動作方法調用之間保持上傳文件

[HttpPost] 
public string Upload() 
{ 
    //I get the file from HttpRequestBase 
    if (Request.Files.Count > 0) 
    { 
     var file = Request.Files[0]; 
     //Some logic... 
    } 
} 

我發送頭和行數的用戶,然後我需要他來告訴我其他的一些信息之前,我處理再次我的文件。

[HttpPost] 
public string Process(SaveViewModel model) 
{ 
    //I don't want to make the user upload the file again and I want to use it here. 
} 

我試着將文件存儲在Session(是的,我知道是不是一個好的做法),但它不工作,當我試圖檢索文件,它帶有ContentLenght = 0,它保持了名稱和除了內容外,其他內容均爲空。有沒有人有另一種方式來做到這一點?

編輯1:顯示更多的代碼,以查看顯示正在進行的會話。

[HttpPost] 
    public string PreUpload() 
    { 
     //Check if request has files 
     if (Request.Files.Count > 0) 
     { 
      var file = Request.Files[0]; 
      //Process the file using CsvHelper 
      using (var sr = new StreamReader(file.InputStream)) 
      {         
       //Initialize the CsvReader 
       var reader = new CsvReader(sr); 
       reader.Read(); 
       //Get the Headers 
       var headers = reader.FieldHeaders; 
       //get how many lines does the file has to inform the user 
       sr.DiscardBufferedData(); 
       sr.BaseStream.Seek(0, System.IO.SeekOrigin.Begin); 
       var lines = sr.ReadToEnd().Split(new char[] { '\n' }); 
       var linesCount = lines.Count() - 1; 
       //Create a ViewModel to send to my view 
       var viewModel = new UploadViewModel() { Headers = headers, ClientsCount = linesCount }; 
       var json = new JavaScriptSerializer().Serialize(viewModel); 
       //Save in sesion 
       Session["file"] = file; 
       //Return my viewModel in a json 
       return json; 

If I break point before I assign the value to the Session

這是我在我的第二個方法讓

[HttpPost] 
public string Save(SaveViewModel model) 
{ 
    //Get the file from session 
    var file = Session["file"] as HttpPostedFileBase; 

If I break point after retrieving

+0

'有沒有人有另一種方法來做到這一點?會話不會隨機破壞數據。你犯了一個錯誤。發佈代碼。 – usr

+3

可能最好將文件移動到臨時目錄,並使用隨機生成的名稱,並將該名稱存儲在會話中。只要確保訂閱Session_End事件以刪除剩餘的文件,如果用戶離開 –

+0

@usr我把更多的信息告訴你怎麼回事會話狀態 –

回答

0

有關生成一個GUID的文件名,這樣,上載時,它保存在什麼數據庫也。您將擁有視圖模型的關鍵(guid)來控制過程。如果發生致命錯誤或用戶放棄任務,則必須執行子例程(每天n次)以刪除密鑰(guid)未完整處理的文件。

相關問題