在web页面前端控件:
<form id="form1" runat="server">
<div style=" height:130px;">
<asp:FileUpload ID="file" runat="server"/><asp:Button runat="server" Text="上传" OnClick="FileUp"/>
</div>
<div style=" height:300px;">
<asp:LinkButton runat="server" OnClick="HrefClik">下载</asp:LinkButton>
</div>
</form>
在.cs后台文件中,
文件的上传为:
声明一个全局变量,记录上传的路径:
private static string docPath = "";
//附件
System.Web.HttpFileCollection contentFile = System.Web.HttpContext.Current.Request.Files;
string fileName = string.Empty;
string newFileName = string.Empty;
string contentPath = string.Empty;
for (int iFile = 0; iFile < contentFile.Count; iFile++)
{
HttpPostedFile postedFile = contentFile[iFile];
fileName = System.IO.Path.GetFileName(postedFile.FileName);
if (fileName != "")
{
if (postedFile.ContentLength > 20 * 1024 * 1024)//限定文件大小
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('上传文件大小不得大于20M');", true);
return;
}
//上传文件类型判断
String filetype = contentFile[iFile].FileName.Substring(contentFile[iFile].FileName.LastIndexOf(".") + 1);
if (!(filetype.Equals("doc") || filetype.Equals("docx") || filetype.Equals("JPG") || filetype.Equals("jpg")))
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('只能上传doc,docx格式的文件或者jpg图片');", true);
return;
}
fileName = (contentFile[iFile].FileName.LastIndexOf("\\") >= 0 ? contentFile[iFile].FileName.Substring(contentFile[iFile].FileName.LastIndexOf("\\") + 1) : contentFile[iFile].FileName);
newFileName = Guid.NewGuid().ToString() + "." + filetype;
contentPath = Server.MapPath("/SendMsgUpFile/" + newFileName);//文件在服务器中存储的路径
docPath = "/SendMsgUpFile/" + newFileName;
if (System.IO.File.Exists(contentPath))
{
this.Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('服务器上已经存在同名文件,请使用其他文件名!');", true);
return;
}
contentFile[iFile].SaveAs(contentPath);
}
}
Response.Write("上传成功");
文件的下载:
//下载
string filename = "";
string filepath = Server.UrlDecode(docPath);
filename = Server.MapPath(filepath);
Response.ContentType = "application/x-zip-compressed";
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename));
Response.TransmitFile(filepath);
相关Demo:http://download.youkuaiyun.com/detail/hugaozhuang/5630815