你的位置:首页 > ASP.net教程

[ASP.net教程]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     else101     {102       if (filename == null || filename == "")103       {104         res = "2";105       }106       else107       {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         else129         {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='http://www.cnblogs.com//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   }