C#上傳附件,以及下載實現


通常情況下,我們會遇到各種上傳附件的情況,以及上傳后需要下載,文檔格式各種各樣,當然這個過程中也是報不同錯誤,還是一個原則,具體問題,具體分析:需求圖:

上傳代碼實現:

 aspx代碼:

 1 <asp:Panel ID="Panel5" runat="server">
 2                 <fieldset>
 3                     <legend>整體活動效果:</legend>
 4                     <nav class="navbar navbar-default" role="navigation">
 5                         <table cellspacing="0" class="table table-hover" border="0" style="border-collapse: collapse;">
 6                             <tbody>
 7                                 <tr>
 8                                     <td><strong>需求單名稱</strong></td>
 9                                     <td colspan="2">
10                                         <strong>添加附件</strong>
11                                     </td>
12                                     <td>附件名稱</td>
13                                 </tr>
14                                 <tr>
15                                     <td><asp:Literal ID="LtOrder" runat="server"></asp:Literal></td>
16                                     <td>
17                                       <asp:Button style="margin-right: -55px;" ID="btnImport" runat="server" Text="添加附件" class="btn btn-default" OnClick="btnImport_Click" /></td>
18                                     <td class="Up_file">
19                                         <asp:FileUpload ID="UpLoadTxt" runat="server" class="form-control" />
20                                     </td>
21                                     <td>
22                                         <asp:Literal ID="LAccessory" runat="server"></asp:Literal>
23                                     </td>
24                                 </tr>
25                             </tbody>
26                         </table>
27                     </nav>
28                 </fieldset>
29             </asp:Panel>

cs代碼:

  1     #region///上傳,文件名稱添加數據庫,文件保存相應路徑
  2     /// <summary>
  3     /// 添加附件
  4     /// </summary>
  5     /// <param name="sender"></param>
  6     /// <param name="e"></param>
  7     protected void btnImport_Click(object sender, EventArgs e)
  8     {
  9         string res = "0";
 10         string fileName = UpLoadTxt.FileName;//獲取要導入的文件名  
 11         if (fileName == null || fileName == "")
 12         {
 13             res = "2";
 14         }
 15         else
 16         {
 17             string savePath = Server.MapPath("~/UploadFiles/ChatLog/");
 18             FileOperatpr(fileName, savePath);
 19             string url = savePath + fileName;
 20             UpLoadTxt.SaveAs(url);
 21             SqlConnection conn = SqlHelperEx.ConnOpen("SPSDB");
 22             string ExtName = getFileExt(fileName).ToUpper();//獲取上傳文件名稱
 23            // string ENDNmae = getFileEND(fileName).ToUpper(); //后綴名
 24             id = Request["id"];
 25             res = GetAccessory(conn, fileName, id);
 26             SqlHelperEx.ConnClose(conn);
 27         }
 28         if (res == "2")
 29         {
 30             Response.Write("<script>alert('沒有要添加的文件,請選中文件后再操作!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request["id"] + "';</script>");
 31         }
 32         if (res == "0")
 33         {
 34             Response.Write("<script>alert('添加失敗!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request["id"] + "';</script>");
 35         }
 36         if(res=="1") {
 37             Response.Write("<script>alert('添加成功!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request["id"] + "';</script>");
 38         }
 39         if (res == "3")
 40         {
 41             Response.Write("<script>alert('沒有需求單,非法操作!');window.location.href='SNSNeedingOrder_InfoListView.aspx?id=" + Request["id"] + "';</script>");
 42         }
 43     }
 44     #region 輔助功能
 45     /// <summary>
 46     /// 獲取上傳文件的后綴名
 47     /// </summary>
 48     /// <param name="fileName"></param>
 49     /// <returns></returns>
 50     private string getFileEND(string fileName)
 51     {
 52         if (fileName.IndexOf(".") == -1)
 53             return "";
 54         string[] temp = fileName.Split('.');
 55         return temp[temp.Length - 1].ToLower();
 56     }
 57     /// <summary>
 58     /// //獲取上傳文件的名稱
 59     /// </summary>
 60     /// <param name="fileName"></param>
 61     /// <returns></returns>
 62     private string getFileExt(string fileName)
 63     {
 64         if (fileName.IndexOf(".") == -1)
 65             return "";
 66         string file = "";
 67         string[] temp = fileName.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries);
 68         file = temp[0].ToLower();
 69         return file.ToLower();
 70     }
 71 
 72 
 73     private void FileOperatpr(string fileName, string savePath)
 74     {
 75         if (!Directory.Exists(savePath))
 76         {
 77             Directory.CreateDirectory(savePath);
 78         }
 79         if (File.Exists(savePath + fileName))
 80         {
 81             File.Delete(savePath + fileName);
 82         }
 83     }
 84 
 85     #endregion
 86 
 87     /// <summary>
 88     /// 添加文件名
 89     /// </summary>
 90     /// <param name="conn"></param>
 91     /// <param name="filename"></param>
 92     /// <param name="id"></param>
 93     private string GetAccessory(SqlConnection conn, string filename, string id)
 94     {
 95         string res = "0";
 96         if (id == "0" || id == "" || id == null)
 97         {
 98             res = "3";
 99         }
100         else
101         {
102             if (filename == null || filename == "")
103             {
104                 res = "2";
105             }
106             else
107             {
108                 string strOrderID = id;
109                 string strFileName = filename;
110                 string strCreateUserId = Session["UserName"].ToString();
111                 StringBuilder strSql = new StringBuilder();
112                 // 生成SQL語句;
113                 strSql.AppendFormat("INSERT INTO BaseSNSAccessory(OrderID,FileName,CreateUserId) values(  {0}", Environment.NewLine);
114                 strSql.AppendFormat(" @OrderID,@FileName,@CreateUserId) {0}", Environment.NewLine);
115                 SqlParameter[] parameters = {
116                                             new SqlParameter("@OrderID", strOrderID),
117                                             new SqlParameter("@FileName", strFileName),
118                                             new SqlParameter("@CreateUserId", strCreateUserId),
119                                             };
120                 // 執行
121                 int result = SqlHelperEx.ExecuteNonQuery(strSql.ToString(), conn, parameters);
122                 // 返回
123                 SqlHelperEx.ConnClose(conn);
124                 if (result == 1)
125                 {
126                     res = "1";
127                 }
128                 else
129                 {
130                     res = "0";
131                 }
132             }
133         }
134         return res;
135     }
136     #endregion

下載實現:

 1 /// <summary>
 2     /// 獲取附件
 3     /// </summary>
 4     /// <param name="conn"></param>
 5     /// <param name="id"></param>
 6     public void GetAccessory(SqlConnection conn, string id)
 7     {
 8         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";
 9         DataTable dt = SqlHelperEx.GetDataTable(strsql, conn);
10         if (dt.Rows.Count == 0)
11         {
12             Ltlog.Text = "無數據";
13             return;
14         }
15         string fileName = "";
16         string str = "";
17         for (int i = 0; i < dt.Rows.Count; i++)
18         {
19             fileName = dt.Rows[i]["FileName"].ToString();
20             str += "<tr height=\"36\" bgcolor=\"#FFFFFF\">";
21             str += "<td>" + dt.Rows[i]["OrderName"].ToString() + "</td>";
22             str += "<td>  <a href='/EcBossWeb/UploadFiles/ChatLog/" + fileName + "' >點擊下載:" + fileName + "</a></td>";
23             str += " </tr>";
24         }
25         LtOrdersory.Text = str.ToString();
26 
27         //string filePath = "";
28 
29         //FileStream fs = new FileStream(filePath, FileMode.Open); // 設置文件流,filePath為文件路徑
30         //byte[] bytes = new byte[(int)fs.Length];
31         //fs.Read(bytes, 0, bytes.Length); // 讀取
32         //fs.Close();
33         //Response.ClearContent(); // 清楚緩沖區所有內容
34         //Response.ClearHeaders(); // 清楚緩沖區所有頭
35         //Response.ContentType = "application/octet-stream"; // 設置輸出流的Http MIME類型
36         ////通知瀏覽器下載文件而不是打開
37         //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //fileName為需要下載的文件名
38         //Response.BinaryWrite(bytes); // 寫入輸入流
39         //Response.Flush(); // 向客戶端發送數據流
40         //Response.End();
41     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM