正在 Controller 中咱们能够运用 FileResult 向存户端发送资料。
; w" D) l( T0 `* Q- q" ^; P( G# s- g% |5 \. R
FileResult. }- J3 y$ g w/ z U" l+ t
6 f1 a5 c. [4 q, [% b: K# A9 L! J
FileResult 是一度形象类,承继自 ActionResult。正在 System.Web.Mvc.dll 中,它有如上三个子类,辨别以没有同的形式向存户端发送资料。5 j$ X1 t4 _- {- U' ~
/ k4 I$ U# {! W9 z6 Y- u2 p 正在实践运用中咱们一般没有需求间接范例化一度 FileResult 的子类,由于 Controller 类曾经需要了六个 File 办法来简化咱们的操作:% J6 D% p( D9 y/ N
% [' N0 }6 m* \/ {" v8 r protected internal FilePathResult File(string fileName, string contentType);protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);protected internal FileContentResult File(byte[] fileContents, string contentType);protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);protected internal FileStreamResult File(Stream fileStream, string contentType);protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
! m. s/ b; w: j+ y" P; d4 d2 P; D) @' r: v( U: g& d) l
FilePathResult
2 A5 h9 W% j1 a2 L$ o- D/ R& S3 M* Y& x5 Y. e5 \
FilePathResult 间接将磁盘上的资料发送至阅读器:( X/ q0 C" E& h) U5 w: r4 P0 V
4 j: R2 n' n& {9 v$ k
1. 最容易的形式; F' K$ n* t4 H# a
$ k' k7 ^) o5 S; l2 [ public ActionResult FilePathDownload1(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File(path, "application/x-zip-compressed");
2 y* t" u$ B& n. }2 L1 w% Z9 G$ |- H$ ^- V: l9 k
第一度参数指名资料门路,第二个参数指名资料的 MIME 类型。用户点击阅读器上的键入链接后,会调出键入窗口:$ Q$ P, u8 |7 g* ~ g
6 n8 L# e1 E4 K 自己该当留意到,资料称号会成为 Download1.zip,默许成了 Action 的名字。咱们运用 File 办法的第二个重载来处理资料名的成绩:2 d, m G/ ]% k! V& X
, R }9 l7 X* s
2. 指名 fileDownloadName* W4 G/ Q d- e, a
& ]! E: ~: d5 \' { public ActionResult FilePathDownload2(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File("g:\\鹤冲天.zip", "application/x-zip-compressed", "crane.zip");}public ActionResult FilePathDownload3(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); var name = Path.GetFileName(path); return File(path, "application/x-zip-compressed", name);}9 F$ B5 P y3 }1 j) _
5 i( t; A! S9 A! i1 h, P. A9 A9 z7 V7 h
咱们能够经过给 fileDownloadName 参数传值来指名资料名,fileDownloadName
/ N8 G! ]# ~" ]3 e
9 I/ g* L. |( m1 h# Y% Y0 k% b7 g 无须和磁盘上的资料名一样。键入提醒窗口辨别如次:FilePathDownload2 没成绩,FilePathDownload3 还是默以为了 Action 的名字。缘由是
, v+ }! j L4 l, |7 }6 k$ t2 x9 e2 x9 g
fileDownloadName 将作为 URL 的一全体,只能蕴含 ASCII 码。咱们把 FilePathDownload3 改良一下:3. 对于 fileDownloadName 停止 Url 补码public ActionResult FilePathDownload4()
# `5 f% |/ v% l1 w# Z+ H5 L( b; B+ f V+ B
{
+ }4 Z1 r' x; Q/ f, I. y3 r# ^3 {7 j: p% c0 d1 [
var path = Server.MapPath("~/Files/鹤冲天.zip");' M( O4 e/ n$ W; H" V& I! Y
) C$ S8 g! S0 L5 h" Z: H
var name = Path.GetFileName(path);1 \7 ^' P2 O6 \
& A$ o6 J2 H* S4 [6 n7 h, Q; l
return File(path, "application/x-zip-compressed", Url.Encode(name));
1 ]+ e% L2 i$ w% O/ J; | o; M) S8 r+ G* {( Y" @4 r& j
}1 y9 H7 w# k1 ^& @
0 i! j. [5 B r" C( y} |