Bue*_*KoW 6 c# inputstream httppostedfilebase asp.net-mvc-2
早上好 - 我试图将HttpPostedFileBase(它总是一个简单的CSV文件)保存到会话变量,如下所示:
[HttpPost]
public ActionResult Index(HttpPostedFileBase importFile) {
Session.Remove("NoteImport");
var noteImport = new NoteImport { ImportFile = importFile, HeaderList = NoteService.HeaderList(importFile) };
Session["NoteImport"] = noteImport;
return RedirectToAction("FileNote");
}
Run Code Online (Sandbox Code Playgroud)
如您所见,我将importFile转储到我的NoteImport类中.目前,ImportFile属性是可公开访问的HttpPostedFileBase类型.
我第一次在我的服务中使用此属性(创建标题值列表的方法),我没有问题:
public List<string> HeaderList(HttpPostedFileBase fileStream) {
var sr = new StreamReader(fileStream.InputStream);
var headerString = sr.ReadLine();
var headerArray = headerString.Split(',');
var headerList = new List<string>();
foreach (var header in headerArray) {
if (!ValidateHeader(header))
throw new InvalidDataException("Invalid header name: " + header);
headerList.Add(header);
}
return headerList;
}
Run Code Online (Sandbox Code Playgroud)
以上工作正常,并返回我目前所需要的.
我的问题是下面的代码.当我调用ReadLine()时,它不会从HttpPostedFileBase中获取任何内容.
public List<string> ImportFileStream(HttpPostedFileBase importFile) {
var sr = new StreamReader(importFile.InputStream);
var headerString = sr.ReadLine();
var headerArray = headerString.Split(',');
var cb = new DelimitedClassBuilder("temp", ",") { IgnoreFirstLines = 0, IgnoreEmptyLines = true, Delimiter = "," };
foreach (var header in headerArray) {
cb.AddField(header, typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
}
var engine = new FileHelperEngine(cb.CreateRecordClass());
var dataTable = engine.ReadStreamAsDT(sr);
var noteData = new List<string>();
var jsonSerializer = new JsonSerializeDataRow();
foreach (var row in dataTable.Rows) {
var dataRow = row as DataRow;
var jsonRow = jsonSerializer.Serialize(dataRow);
noteData.Add(jsonRow);
}
return noteData;
}
Run Code Online (Sandbox Code Playgroud)
我试图关闭HttpPostedFileBase; 我还将流位置设置为0.似乎没有任何进展.我有一种感觉,我需要在保存到会话之前将其更改为其他类型.
任何建议?
谢谢!
您无法将一个存储HttpPostedFileBase到会话中。这只是没有道理。它包含一个指向HTTP请求流中文件内容的流,该流在请求结束时被垃圾回收。您需要先将其序列化为一些自定义对象,然后再存储到会话中。例如:
public class MyFile
{
public string Name { get; set; }
public string ContentType { get; set; }
public byte[] Contents { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在继续并将其存储到会话中。当然,您应该注意,这样做是将整个文件内容存储到内存中,这可能不是您想要执行的操作,特别是如果上传的文件可能很大。另一种可能性是将文件内容存储到磁盘或数据库之类的可持久介质中,并且仅将指向该介质的指针存储到会话中,以便以后可以检索它。