首先应该写一个导航页面,它向你的ashx文件提交数据。可以创建一个aspx,名叫TestPostFile.aspx,如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="TestPostFile.aspx.cs" Inherits="TestPostFile" EnableViewState="false" ClientIDMode="Static" %> <!DOCTYPE html> < html xmlns = "http://www.w3.org/1999/xhtml" > < head runat = "server" > < meta http-equiv = "Content-Type" content = "text/html; charset=utf-8" /> < title ></ title > </ head > < body > < form id = "form1" runat = "server" > < asp:Label ID = "Label1" runat = "server" Text = "参数xyz" ></ asp:Label >:< asp:TextBox ID = "xyz" runat = "server" ></ asp:TextBox > < hr /> < asp:FileUpload ID = "FileUpload1" runat = "server" /> < hr /> < asp:Button ID = "Button1" runat = "server" Text = "好,可以提交了!" /> </ form > </ body > </ html > |
注意,因为无需回发,因此我们禁用页面的ViewState。同时由于实在是太简单了,因此我们使用Static模式来处理客户端id。
这个文件的codebehind代码是
1
2
3
4
5
6
7
8
9
|
using System; public partial class TestPostFile : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e) { this .form1.Action = "TestPostFile.ashx" ; } } |
它在提交数据时,提交了一个文本内容,同时提交了一个文件。你当然可以放上去更多的提交内容。
而目标ashx文件可以这样写
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
<%@ WebHandler Language= "C#" Class= "TestPostFile" %> using System; using System.Web; using System.Diagnostics; public class TestPostFile : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain" ; var p1 = context.Request.Form[ "xyz" ]; var fs = context.Request.Files; if (fs.Count > 0) { //你可以使用 fs[0].SaveAs(.....) 保存文件 context.Response.Write(fs[0].FileName); } Debug.Assert(p1 != null && fs != null ); } public bool IsReusable { get { return false ; } } } |