正在 Controller 中咱们能够运用 FileResult 向存户端发送资料。
' p' n/ E4 {- C9 g4 Y' l/ C- ~' Y& M" B0 j* v0 X
FileResult/ q3 k6 X$ X/ f+ D0 `" q
+ v; l6 Y6 x8 K3 C; n2 [
FileResult 是一度形象类,承继自 ActionResult。正在 System.Web.Mvc.dll 中,它有如上三个子类,辨别以没有同的形式向存户端发送资料。
, w/ ]" }0 H7 h; u
~/ C2 j% V2 Z/ M. v( v 正在实践运用中咱们一般没有需求间接范例化一度 FileResult 的子类,由于 Controller 类曾经需要了六个 File 办法来简化咱们的操作:
5 o' M; ~& o: X1 T
4 V- p* W* h$ T 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);
- I8 W+ q3 h6 ]' }0 l( _: ^
+ _& V5 W5 ]2 n$ H FilePathResult# Z# V; _; k. [4 U9 V( s
9 }8 u) @8 e- f) ~/ b7 I FilePathResult 间接将磁盘上的资料发送至阅读器:
( t, a* [' K: `) J' o O& t- p/ \! V( M& k* |& S
1. 最容易的形式
( T0 ^& z H0 ?2 E. P! y" I h
6 S4 t' d" R3 n; W- [& I public ActionResult FilePathDownload1(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File(path, "application/x-zip-compressed");
( n7 R+ q& U: p; O3 y6 U% |- s6 K
' m, e2 G$ r7 u5 C: J o 第一度参数指名资料门路,第二个参数指名资料的 MIME 类型。用户点击阅读器上的键入链接后,会调出键入窗口:
6 J. e# S& w5 N+ U" H9 Y/ T1 |, o% D( @! F) V) G' E1 E
自己该当留意到,资料称号会成为 Download1.zip,默许成了 Action 的名字。咱们运用 File 办法的第二个重载来处理资料名的成绩:
1 v1 I* Y; @8 l3 o& Y, Z8 n& o$ v- ~6 f9 b. F9 D3 q1 u
2. 指名 fileDownloadName) I" R4 h" n5 y* S0 f
* v+ ^- g( l( M2 b8 Q6 I" @ 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);}
6 D$ y2 J# q' z, J7 ~; L1 ?6 M% _
咱们能够经过给 fileDownloadName 参数传值来指名资料名,fileDownloadName : x* N) U) F' _9 Q6 e
' R! b3 A g5 K" {8 y: @
无须和磁盘上的资料名一样。键入提醒窗口辨别如次:FilePathDownload2 没成绩,FilePathDownload3 还是默以为了 Action 的名字。缘由是
8 o; L- k+ b" U0 M* ?9 x
/ t2 ^4 K5 A+ _7 ]# k$ [ fileDownloadName 将作为 URL 的一全体,只能蕴含 ASCII 码。咱们把 FilePathDownload3 改良一下:3. 对于 fileDownloadName 停止 Url 补码public ActionResult FilePathDownload4()1 I4 s1 S. g% i8 }4 r6 c
& I4 q4 ~2 o' |# y" |" Z H, |5 Z
{
N$ D2 Q: {+ I# n: y7 l" V# C3 j1 P2 l1 R4 ^1 A3 `6 V" F
var path = Server.MapPath("~/Files/鹤冲天.zip");: w5 Y/ V: E" u! u- @, f+ ?2 d9 j/ P
% o9 o# F, ^" P& o; S
var name = Path.GetFileName(path);& V+ q+ e) Q0 e4 L: B# w
~7 q$ Q. H0 `* Z7 v& b$ w9 J return File(path, "application/x-zip-compressed", Url.Encode(name));. y% {/ G f2 Q$ u: W
) E; ?/ ~1 j7 _( O }
8 @7 f6 ^. L- x! v7 }( W: I9 k
9 z3 I+ }' M7 }* @+ k5 D+ x3 b$ S} |