通常情況下,我們會遇到各種上傳附件的情況,以及上傳后需要下載,文檔格式各種各樣,當然這個過程中也是報不同錯誤,還是一個原則,具體問題,具體分析:需求圖:
上傳代碼實現:
aspx代碼:
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
|
< asp:Panel ID = "Panel5" runat = "server" > < fieldset > < legend >整體活動效果:</ legend > < nav class = "navbar navbar-default" role = "navigation" > < table cellspacing = "0" class = "table table-hover" border = "0" style = "border-collapse: collapse;" > < tbody > < tr > < td >< strong >需求單名稱</ strong ></ td > < td colspan = "2" > < strong >添加附件</ strong > </ td > < td >附件名稱</ td > </ tr > < tr > < td >< asp:Literal ID = "LtOrder" runat = "server" ></ asp:Literal ></ td > < td > < asp:Button style = "margin-right: -55px;" ID = "btnImport" runat = "server" Text = "添加附件" class = "btn btn-default" OnClick = "btnImport_Click" /></ td > < td class = "Up_file" > < asp:FileUpload ID = "UpLoadTxt" runat = "server" class = "form-control" /> </ td > < td > < asp:Literal ID = "LAccessory" runat = "server" ></ asp:Literal > </ td > </ tr > </ tbody > </ table > </ nav > </ fieldset > </ asp:Panel > |
cs代碼:
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
|
#region///上傳,文件名稱添加數據庫,文件保存相應路徑 /// <summary> /// 添加附件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnImport_Click( object sender, EventArgs e) { string res = "0" ; string fileName = UpLoadTxt.FileName; //獲取要導入的文件名 if (fileName == null || fileName == "" ) { res = "2" ; } else { string savePath = Server.MapPath( "~/UploadFiles/ChatLog/" ); FileOperatpr(fileName, savePath); string url = savePath + fileName; UpLoadTxt.SaveAs(url); SqlConnection conn = SqlHelperEx.ConnOpen( "SPSDB" ); string ExtName = getFileExt(fileName).ToUpper(); //獲取上傳文件名稱 // string ENDNmae = getFileEND(fileName).ToUpper(); //后綴名 id = Request[ "id" ]; res = GetAccessory(conn, fileName, id); SqlHelperEx.ConnClose(conn); } if (res == "2" ) { Response.Write( "<script>alert('沒有要添加的文件,請選中文件后再操作!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request[ "id" ] + "';</script>" ); } if (res == "0" ) { Response.Write( "<script>alert('添加失敗!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request[ "id" ] + "';</script>" ); } if (res== "1" ) { Response.Write( "<script>alert('添加成功!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request[ "id" ] + "';</script>" ); } if (res == "3" ) { Response.Write( "<script>alert('沒有需求單,非法操作!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request[ "id" ] + "';</script>" ); } } #region 輔助功能 /// <summary> /// 獲取上傳文件的后綴名 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string getFileEND( string fileName) { if (fileName.IndexOf( "." ) == -1) return "" ; string [] temp = fileName.Split( '.' ); return temp[temp.Length - 1].ToLower(); } /// <summary> /// //獲取上傳文件的名稱 /// </summary> /// <param name="fileName"></param> /// <returns></returns> private string getFileExt( string fileName) { if (fileName.IndexOf( "." ) == -1) return "" ; string file = "" ; string [] temp = fileName.Split( new [] { "." }, StringSplitOptions.RemoveEmptyEntries); file = temp[0].ToLower(); return file.ToLower(); } private void FileOperatpr( string fileName, string savePath) { if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } if (File.Exists(savePath + fileName)) { File.Delete(savePath + fileName); } } #endregion /// <summary> /// 添加文件名 /// </summary> /// <param name="conn"></param> /// <param name="filename"></param> /// <param name="id"></param> private string GetAccessory(SqlConnection conn, string filename, string id) { string res = "0" ; if (id == "0" || id == "" || id == null ) { res = "3" ; } else { if (filename == null || filename == "" ) { res = "2" ; } else { string strOrderID = id; string strFileName = filename; string strCreateUserId = Session[ "UserName" ].ToString(); StringBuilder strSql = new StringBuilder(); // 生成SQL語句; strSql.AppendFormat( "INSERT INTO BaseSNSAccessory(OrderID,FileName,CreateUserId) values( {0}" , Environment.NewLine); strSql.AppendFormat( " @OrderID,@FileName,@CreateUserId) {0}" , Environment.NewLine); SqlParameter[] parameters = { new SqlParameter( "@OrderID" , strOrderID), new SqlParameter( "@FileName" , strFileName), new SqlParameter( "@CreateUserId" , strCreateUserId), }; // 執行 int result = SqlHelperEx.ExecuteNonQuery(strSql.ToString(), conn, parameters); // 返回 SqlHelperEx.ConnClose(conn); if (result == 1) { res = "1" ; } else { res = "0" ; } } } return res; } #endregion |
下載實現:
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
32
33
34
35
36
37
38
39
40
41
|
/// <summary> /// 獲取附件 /// </summary> /// <param name="conn"></param> /// <param name="id"></param> public void GetAccessory(SqlConnection conn, string id) { string strsql = "SELECT *,(SELECT OrderName FROM Order_Info WHERE IsValid=1 AND id=bs.OrderID AND IsValid=1) AS OrderName FROM BaseSNSAccessory AS bs WHERE bs.IsValid=1 and bs.OrderID=" +id+ " ORDER BY bs.id DESC" ; DataTable dt = SqlHelperEx.GetDataTable(strsql, conn); if (dt.Rows.Count == 0) { Ltlog.Text = "無數據" ; return ; } string fileName = "" ; string str = "" ; for ( int i = 0; i < dt.Rows.Count; i++) { fileName = dt.Rows[i][ "FileName" ].ToString(); str += "<tr height=\"36\" bgcolor=\"#FFFFFF\">" ; str += "<td>" + dt.Rows[i][ "OrderName" ].ToString() + "</td>" ; str += "<td> <a href='/EcBossWeb/UploadFiles/ChatLog/" + fileName + "' >點擊下載:" + fileName + "</a></td>" ; str += " </tr>" ; } LtOrdersory.Text = str.ToString(); //string filePath = ""; //FileStream fs = new FileStream(filePath, FileMode.Open); // 設置文件流,filePath為文件路徑 //byte[] bytes = new byte[(int)fs.Length]; //fs.Read(bytes, 0, bytes.Length); // 讀取 //fs.Close(); //Response.ClearContent(); // 清楚緩沖區所有內容 //Response.ClearHeaders(); // 清楚緩沖區所有頭 //Response.ContentType = "application/octet-stream"; // 設置輸出流的Http MIME類型 ////通知瀏覽器下載文件而不是打開 //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //fileName為需要下載的文件名 //Response.BinaryWrite(bytes); // 寫入輸入流 //Response.Flush(); // 向客戶端發送數據流 //Response.End(); } |
以上就是為大家分享的C#實現附件上傳和下載功能的關鍵代碼,希望對大家的學習有所幫助。