正在 Controller 中咱们能够运用 FileResult 向存户端发送资料。7 ]( ]+ f* L8 F6 ?
( N3 p4 \* K1 ^ FileResult
, ?5 f1 g* N! h3 j( f. L6 s+ ~% o. x1 x
FileResult 是一度形象类,承继自 ActionResult。正在 System.Web.Mvc.dll 中,它有如上三个子类,辨别以没有同的形式向存户端发送资料。
6 ^' }& e; E* `& R8 ]+ s0 A5 a- x# F8 C% b+ Q R4 V
正在实践运用中咱们一般没有需求间接范例化一度 FileResult 的子类,由于 Controller 类曾经需要了六个 File 办法来简化咱们的操作:! w5 `" [8 ^" `; h/ j& b
3 s4 W' }. z! y3 B+ g
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);" V8 z6 }7 B( O/ C
- F7 C+ K' S$ y7 r; | FilePathResult
+ H1 x! T: Z( r
3 ~) N! k: n! r( ?$ ~( ~+ T FilePathResult 间接将磁盘上的资料发送至阅读器:
9 N! H2 G: z( M5 f* Z0 {' v
% Z5 M; e- {0 g9 [ 1. 最容易的形式$ }2 ^* q2 B4 \0 f' q& \
) b$ i5 Z% c! c0 |
public ActionResult FilePathDownload1(){ var path = Server.MapPath("~/Files/鹤冲天.zip"); return File(path, "application/x-zip-compressed");
+ I1 D: y3 m6 P% S
0 ~- h" }" u" j+ n! [; E 第一度参数指名资料门路,第二个参数指名资料的 MIME 类型。用户点击阅读器上的键入链接后,会调出键入窗口:9 v1 G' z" \. V5 I' m
, Y6 \: X9 @1 B) \4 a+ B
自己该当留意到,资料称号会成为 Download1.zip,默许成了 Action 的名字。咱们运用 File 办法的第二个重载来处理资料名的成绩:6 U9 s9 |4 J9 }1 a
$ i0 U+ r; Z1 s8 h( O 2. 指名 fileDownloadName2 b# q0 s2 g$ \# d
/ h3 y- B- F* c' a0 G4 D. P
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);}: m1 o: n1 y1 e6 e2 r# A
" l* v6 }& `1 X; C, w3 F8 [ 咱们能够经过给 fileDownloadName 参数传值来指名资料名,fileDownloadName
. L7 i# ~3 X. Z/ X% [3 l
) Z' T4 @7 e. Z w9 v, b6 L6 @6 L 无须和磁盘上的资料名一样。键入提醒窗口辨别如次:FilePathDownload2 没成绩,FilePathDownload3 还是默以为了 Action 的名字。缘由是
1 A- u' x$ V1 E4 _1 G7 E$ u0 l4 u" l9 h
fileDownloadName 将作为 URL 的一全体,只能蕴含 ASCII 码。咱们把 FilePathDownload3 改良一下:3. 对于 fileDownloadName 停止 Url 补码public ActionResult FilePathDownload4()* z( a% B( k Y% Q8 k) a6 M" g
- ^! f/ _. S+ m& U8 r& o {
7 q( w( M* \( l1 e5 q7 ~% b. I) D- @& B, a9 \1 _
var path = Server.MapPath("~/Files/鹤冲天.zip");- N: G& D2 W ?9 M( q7 K
: \' y, ]9 G! ^6 C j
var name = Path.GetFileName(path);" u8 A& o# h' I
2 N6 A: U) X, C D return File(path, "application/x-zip-compressed", Url.Encode(name));
! H0 _; V6 ~; W0 P/ f9 S4 N9 `# e; ~' N- c, Y2 q g
}: b; r) Y2 a! ]$ Q/ j* I
- a# {7 l2 k. P9 k4 h} |