asp.net文件上传和下载
2018-07-20 来源:open-open
.cs代码
/// <summary>
/// 文件上传/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button1_Click(object sender, EventArgs e)
{
string WebPath = HttpContext.Current.Server.MapPath("/UpLoad");//上传到指定的文件夹
string filename = FileImg.PostedFile.FileName;//文件名
//上传文件是否为空
if (FileImg.PostedFile != null && FileImg.PostedFile.ContentLength > 0)
{
string imageType = Path.GetExtension(FileImg.PostedFile.FileName).ToLower();//获取文件格式
string s = ".bmp;.rar;.zip;.iso;.jpg;.jpeg;.gif;.png;.flv;.doc;.docx;.xls;.xlsx;.ppt;.pptx;.txt;.pps;.pdf";
if (s.Split(';').Contains(imageType))
{
//检查是否有此文件夹
if (!Directory.Exists(WebPath))
{
System.IO.Directory.CreateDirectory(WebPath);
}
//上传
FileImg.PostedFile.SaveAs(WebPath + "\\" + filename);
ScriptManager.RegisterStartupScript(this, this.GetType(), "a", "<script>alert('成功上传文件!!')</script>", false);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "a", "<script>alert('格式不正确')</script>", false);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "a", "<script>alert('请上传文件!!')</script>", false);
}
}
/// <summary>
/// 文件下载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Button2_Click(object sender, EventArgs e)
{
string filename = "aaa.txt";
string filepath = Server.MapPath("DownLoad/aaa.txt");
//以字符流的形式下载文件
FileStream fs = new FileStream(filepath, 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(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
前台
<form id="form1" runat="server">
<div>
<input type="file" onchange="previewImage(this)" id="FileImg" runat="server" />
<asp:Button ID="Button1" runat="server" Text="保存图片" OnClick="Button1_Click" Style="height: 21px" />
<br />
<asp:Button ID="Button2" runat="server" Text="文件下载" onclick="Button2_Click" />
</div>
</form>
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
上一篇:iOS 设置app禁止横屏