HttpContext.Current.Response在mvc中下载文件

时间:2017-07-31 12:20:17

标签: c# asp.net-mvc

我在asp.net中有以下代码

 GetObjectResponse resp = Media.ReadS3Object("data", strKey);
            StreamReader sr = new StreamReader(resp.ResponseStream);

            //Prompt download:
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = resp.ContentType; // "text/csv;";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fname));
            HttpContext.Current.Response.BinaryWrite(UTF8Encoding.Convert(Encoding.UTF8, Encoding.Unicode, Encoding.UTF8.GetBytes(sr.ReadToEnd())));
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();

它下载文件,如何通过mvc实现同样的功能。 感谢

1 个答案:

答案 0 :(得分:0)

设置ActionResult以返回文件。

public ActionResult DownloadFile(string strKey) {
    GetObjectResponse resp = Media.ReadS3Object("data", strKey);
    StreamReader sr = new StreamReader(resp.ResponseStream);


    return File(sr, resp.ContentType, fname);
}