正在 Controller 中咱们能够运用 FileResult 向存户端发送资料。
6 v$ i) a/ F. F! f7 G( V( x7 }# K$ ~
, @2 k# K9 [; R4 K) k FileResult4 X5 K7 p- B& h
+ Z t+ {# |+ _" h& h C/ q6 ]* ~
FileResult 是一度形象类,承继自 ActionResult。正在 System.Web.Mvc.dll 中,它有如上三个子类,辨别以没有同的形式向存户端发送资料。+ J. e$ T1 o" W) \8 B4 B
( C/ a0 I% G6 P9 y8 h
正在实践运用中咱们一般没有需求间接范例化一度 FileResult 的子类,由于 Controller 类曾经需要了六个 File 办法来简化咱们的操作:
1 K; _7 K' }# E8 t; ^: l) c( I2 F4 M/ f$ b0 ~' Z2 n3 }* N
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);6 o9 x0 x* L4 t. J2 N* z
0 @& k) P! T! ], s
FilePathResult' q i6 D( D' j3 R" Q
7 Q! K0 ]9 r/ K6 F2 n% ~! V2 N FilePathResult 间接将磁盘上的资料发送至阅读器:1 x& D0 ?5 ^* ~3 T
* B! I) ` u7 G7 I. p! k/ [
1. 最容易的形式+ m3 T- c/ q# U1 V! a" y# Q, k
" [& \1 `2 y! V public ActionResult FilePathDownload1(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File(path, "application/x-zip-compressed");7 M8 U& X' m' {$ x9 U- j
; I( ]4 R! F& W/ T+ C& S5 a
第一度参数指名资料门路,第二个参数指名资料的 MIME 类型。用户点击阅读器上的键入链接后,会调出键入窗口:0 @7 }4 Z+ ]8 T M
6 W1 H F7 i; P" X3 ^, l7 ^ 自己该当留意到,资料称号会成为 Download1.zip,默许成了 Action 的名字。咱们运用 File 办法的第二个重载来处理资料名的成绩:
1 D8 O; u4 S7 C! J8 P4 \: B6 A$ y. `; k
2. 指名 fileDownloadName, f- C( k* p- t9 V
& b& d! V! D0 l' R' C; }8 ?
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);}
! l+ G/ R; d$ B0 ~* c" _$ `4 n {6 R4 t0 G8 r( l$ g0 V
咱们能够经过给 fileDownloadName 参数传值来指名资料名,fileDownloadName 7 I# W: ?# u9 Y' x/ z
) v2 }# D/ t5 K
无须和磁盘上的资料名一样。键入提醒窗口辨别如次:FilePathDownload2 没成绩,FilePathDownload3 还是默以为了 Action 的名字。缘由是
- w/ R. }( N9 H0 _7 g6 o$ M1 B
3 b" |% W6 ^! f( o2 J fileDownloadName 将作为 URL 的一全体,只能蕴含 ASCII 码。咱们把 FilePathDownload3 改良一下:3. 对于 fileDownloadName 停止 Url 补码public ActionResult FilePathDownload4()
, @# z' P3 [4 B+ M
4 |* g+ N3 t# Y: N! z$ d1 c$ O {: Y( n7 S1 n$ y
A+ i" A% M3 E/ `4 m8 H var path = Server.MapPath("~/Files/鹤冲天.zip");
) H3 a2 J) z- K) n' f- l) C! q0 F6 [
var name = Path.GetFileName(path);
5 Q$ _& j2 o3 @) x9 k J; b
6 S/ H6 G2 M" g, i. a' s return File(path, "application/x-zip-compressed", Url.Encode(name));- H& A9 {0 \- l% q! t8 q: c3 G
1 g6 W8 w! {' k) t4 N
}# F( `$ c. `5 C
+ X* T2 R1 w' h; A2 E# W
} |