C#實(shí)現(xiàn)附件上傳和下載功能
通常情況下,我們會遇到各種上傳附件的情況,以及上傳后需要下載,文檔格式各種各樣,當(dāng)然這個過程中也是報不同錯誤,還是一個原則,具體問題,具體分析:需求圖:

上傳代碼實(shí)現(xiàn):
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///上傳,文件名稱添加數(shù)據(jù)庫,文件保存相應(yīng)路徑
/// <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;//獲取要導(dǎo)入的文件名
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),
};
// 執(zhí)行
int result = SqlHelperEx.ExecuteNonQuery(strSql.ToString(), conn, parameters);
// 返回
SqlHelperEx.ConnClose(conn);
if (result == 1)
{
res = "1";
}
else
{
res = "0";
}
}
}
return res;
}
#endregion
下載實(shí)現(xiàn):
/// <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 = "無數(shù)據(jù)";
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 + "' >點(diǎn)擊下載:" + fileName + "</a></td>";
str += " </tr>";
}
LtOrdersory.Text = str.ToString();
//string filePath = "";
//FileStream fs = new FileStream(filePath, FileMode.Open); // 設(shè)置文件流,filePath為文件路徑
//byte[] bytes = new byte[(int)fs.Length];
//fs.Read(bytes, 0, bytes.Length); // 讀取
//fs.Close();
//Response.ClearContent(); // 清楚緩沖區(qū)所有內(nèi)容
//Response.ClearHeaders(); // 清楚緩沖區(qū)所有頭
//Response.ContentType = "application/octet-stream"; // 設(shè)置輸出流的Http MIME類型
////通知瀏覽器下載文件而不是打開
//Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8)); //fileName為需要下載的文件名
//Response.BinaryWrite(bytes); // 寫入輸入流
//Response.Flush(); // 向客戶端發(fā)送數(shù)據(jù)流
//Response.End();
}
以上就是為大家分享的C#實(shí)現(xiàn)附件上傳和下載功能的關(guān)鍵代碼,希望對大家的學(xué)習(xí)有所幫助。
- C#實(shí)現(xiàn)的文件上傳下載工具類完整實(shí)例【上傳文件自動命名】
- C#利用SFTP實(shí)現(xiàn)上傳下載
- C# 文件上傳下載(Excel導(dǎo)入,多線程下載)功能的實(shí)現(xiàn)代碼
- C#實(shí)現(xiàn)文件上傳下載Excel文檔示例代碼
- C#實(shí)現(xiàn)文件上傳及文件下載功能實(shí)例代碼
- C#文件上傳與下載的實(shí)現(xiàn)方法
- C#開發(fā)教程之FTP上傳下載功能詳解
- C#實(shí)現(xiàn)文件上傳與下載功能實(shí)例
- 關(guān)于c#連接ftp進(jìn)行上傳下載實(shí)現(xiàn)原理及代碼
- C#實(shí)現(xiàn)上傳下載圖片
相關(guān)文章
聊聊C# 中HashTable與Dictionary的區(qū)別說明
這篇文章主要介紹了聊聊C# 中HashTable與Dictionary的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
C#使用jQuery實(shí)現(xiàn)無刷新評論提交的方法
這篇文章主要介紹了C#使用jQuery實(shí)現(xiàn)無刷新評論提交的方法,涉及C#結(jié)合jQuery進(jìn)行Ajax操作的相關(guān)技巧,非常具有實(shí)用價值,需要的朋友可以參考下2015-05-05
C#實(shí)現(xiàn)Excel導(dǎo)入sqlite的方法
這篇文章主要介紹了C#實(shí)現(xiàn)Excel導(dǎo)入sqlite的方法,是C#程序設(shè)計中非常重要的一個實(shí)用技巧,需要的朋友可以參考下2014-09-09
C# 中將數(shù)值型數(shù)據(jù)轉(zhuǎn)換為字節(jié)數(shù)組的方法
C# 中將數(shù)值型數(shù)據(jù)轉(zhuǎn)換為字節(jié)數(shù)組的方法,需要的朋友可以參考一下2013-05-05

