C# web 上传下载文件

C# web 上传下载文件文件类型不限制,只要客户单有相对应的文件

//上传

//上下文

System.Web.HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
System.Text.StringBuilder strmsg = new System.Text.StringBuilder("");
string[] rd = Request.Form[1].Split(',');//获得图片描述的文本框字符串数组,为对应的图片的描述

//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)//说明图片大小和格式都没问题
{
//以下为创建图库目录
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)//有文件才执行上传操作再保存到数据库
{
FileExtention = System.IO.Path.GetExtension(myFile.FileName);

ppath = dirpath + @"\" + FileName;
//重复提示!
bool flag = File.Exists(ppath);
if (flag == true)
{
Response.Write("<script>alert('"+ppath+" 已经存在,请检查!')</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();

猜你喜欢

转载自www.cnblogs.com/hzf08/p/9020760.html