程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#完成附件上傳和下載功效

C#完成附件上傳和下載功效

編輯:C#入門知識

C#完成附件上傳和下載功效。本站提示廣大學習愛好者:(C#完成附件上傳和下載功效)文章只能為提供參考,不一定能成為您想要的結果。以下是C#完成附件上傳和下載功效正文


平日情形下,我們會碰到各類上傳附件的情形,和上傳後須要下載,文檔格局各類各樣,固然這個進程中也是報分歧毛病,照樣一個准繩,詳細成績,詳細剖析:需求圖:

上傳代碼完成:
 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" >
    <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  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#完成附件上傳和下載功效的症結代碼,願望對年夜家的進修有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved