【发布时间】:2016-04-06 20:02:34
【问题描述】:
我在 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;
这就是我在第二种方法中得到的结果
[HttpPost]
public string Save(SaveViewModel model)
{
//Get the file from session
var file = Session["file"] as HttpPostedFileBase;
【问题讨论】:
-
Does anyone have another way to do it?修复这个错误怎么样?会话不会随机损坏数据。你犯了一个错误。贴出代码。 -
最好将文件移动到一个临时目录,使用随机生成的名称,并将该名称存储在会话中。只需确保订阅 Session_End 事件以在用户离开时删除剩余文件
-
@usr 我放了更多信息来告诉你会话状态发生了什么
-
不要在会话中存储文件。使用临时目录
标签: c# asp.net asp.net-mvc http csv