C#实现附件上传和下载功能
时间:2020-10-11 10:45:26|栏目:.NET代码|点击: 次
通常情况下,我们会遇到各种上传附件的情况,以及上传后需要下载,文档格式各种各样,当然这个过程中也是报不同错误,还是一个原则,具体问题,具体分析:需求图:
上传代码实现:
aspx代码:
<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代码:
#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
下载实现:
/// <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#实现附件上传和下载功能的关键代码,希望对大家的学习有所帮助。