C# web 上传下载文件
C# web 上傳下載文件文件類型不限制,只要客戶單有相對應(yīng)的文件
//上傳
?
//上下文
System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");
string[] rd = Request.Form[1].Split(',');//獲得圖片描述的文本框字符串?dāng)?shù)組,為對應(yīng)的圖片的描述
//string albumid=ddlAlbum.SelectedValue.Trim();
int ifile;
for (ifile = 0; ifile < files.Count; ifile++)
{
if (files[ifile].FileName.Length > 0)
{
System.Web.HttpPostedFile postedfile = files[ifile];
if (postedfile.ContentLength / 1024 > 1024*30)//單個文件不能大于30M
{
strmsg.Append(Path.GetFileName(postedfile.FileName) + "---不能大于30M<br>");
ClientScript.RegisterStartupScript(GetType(), "", "<script>alert('"+strmsg+"');</script>");
return;
}
string fex = Path.GetExtension(postedfile.FileName);
}
}
if (strmsg.Length <= 0)//說明圖片大小和格式都沒問題
{
//以下為創(chuàng)建圖庫目錄
string dirpath = Server.MapPath("~/download/sop"); //項目文件的相對路徑
string ppath = "";
if (Directory.Exists(dirpath) == false)
{
Directory.CreateDirectory(dirpath);
}
for (int i = 0; i < files.Count; i++)
{
System.Web.HttpPostedFile myFile = files[i];
string FileName = "";
string FileExtention = "";
FileName = System.IO.Path.GetFileName(myFile.FileName);
if (FileName.Length > 0)//有文件才執(zhí)行上傳操作再保存到數(shù)據(jù)庫
{
FileExtention = System.IO.Path.GetExtension(myFile.FileName);
ppath = dirpath + @"\" + FileName;
//重復(fù)提示!
bool flag = File.Exists(ppath);
if (flag == true)
{
Response.Write("<script>alert('"+ppath+" 已經(jīng)存在,請檢查!')</script>");
return;
}
myFile.SaveAs(ppath);
txtAttch.Value = FileName;
}
}
System.Threading.Thread.Sleep(150);
if (ppath.Length < 1)
{
Response.Write("<script>alert('請找到符合的文件!')</script>");
return;
}
Response.Write("<script>alert('文件上傳成功!')</script>");
}
?
//下載
string strResult = string.Empty;
string strPath = Server.MapPath(@"~/download/sop"); //項目的相對路徑
LinkButton txtlink = (LinkButton)sender;? ? ? ? ? ? ? ? ? ? ? ?//傳入linkbutton中的值 (gridview 中的)
string strFile = strPath+"\\"+ txtlink.Text;
using (FileStream fs = new FileStream(strFile, FileMode.Open))? //文件流
{
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(strFile, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
?
轉(zhuǎn)載于:https://www.cnblogs.com/hzf08/p/9020760.html
總結(jié)
以上是生活随笔為你收集整理的C# web 上传下载文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 配合cat.jsp批量下载脚本
- 下一篇: 教育部:不得将研究生当作廉价劳动力!