如何在内存中创建文件然后通过asp.net mvc + jquery将文件发送给用户?

我正在使用Dday日历库,我想导出用户日历。 因此,我使用Dday获取所有用户记录并将其转换为ical格式(.ics)。

现在我想把它拿回来并发回给用户。 但是我真的不想先在服务器上生成文件然后将其发送给他们。 如果我可以在内存中进行并将其发送给他们。

但是,如果它有很多工作,我将采取一种方法将其保存在服务器上,允许用户下载它,然后在完成下载后删除它(我不希望文件在我的服务器上更多然后几分钟)。

我也不确定如何将其发送给用户。 我总是喜欢用jquery做一个ajaxpost到服务器然后以某种方式让文件回来并为用户弹出。

再次,如果这是很多工作,我会满足于服务器端的方式,asp.net mvc处理它。

但我不知道该怎么办。

那我该怎么做呢?

您需要使用MVC返回FileStreamResult类型

public FileStreamResult MyFunction(/*your parms*/) { System.IO.MemoryStream stream = FunctionThatCreatesMyCalendarStream(); //you may need stream.Position = 0 here depending on what state above funciton leaves the stream in. //stream.Position = 0; FileStreamResult result = new FileStreamResult(stream, "text/calendar"); result.FileDownloadName = "myfiledownloadname.ics"; return result; } 

您需要一个服务器端处理程序,它将生成数据,将HttpResponse.ContentType设置为相应的MIME类型,然后您需要将数据写入HttpResponse.ResponseStream或使用HttpResponse.Write方法。

示例(CalendarHandler.ashx):

 public class CalendarHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/calendar"; var calendarData = @" BEGIN:VEVENT UID:19970901T130000Z-123402@host.com DTSTAMP:19970901T1300Z DTSTART:19970401T163000Z DTEND:19970402T010000Z SUMMARY:Laurel is in sensitivity awareness class. CLASS:PUBLIC CATEGORIES:BUSINESS,HUMAN RESOURCES TRANSP:TRANSPARENT END:VEVENT"; context.Response.Write(calendarData); } } 

现在,您只需要使用ajax或使用传统方法向CalcHandler.ashx发出请求。

注意:我不知道这是否是一个有效的candelar数据,我只是从RFC http://tools.ietf.org/html/rfc2445中随机抽取了一个例子。

如果这样做,您无需随时创建文件。

你可以使用你自己的行动结果:(不知道DCal做了什么,所以在这里做到了)

 public class DCalResult : ActionResult { private readonly ISomeDCalInterface _dcalObject; public DCalResult(ISomeDCalInterface dcalObject) { _dcalObject = dcalObject; } public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ClearHeaders(); response.ContentType = "text/calendar"; response.Write(_dcalObject.ToString()); } } 

然后在你的控制器动作中返回:

 public ActionResult DCal() { return new DCalResult(usersDcalObject); }