简单的文件上传和下载
上传代码
if (FileUpload1.HasFile)
{
try
{
if (txtCategory.Text == "")
{
Label5.Text = "文档上次失败,请输入上传文档所属类型!";
divGridInformationAsset.Style["Display"] = "Block";
}
else
{
//获取上传文件名
string filename = this.FileUpload1.FileName;
//获取上传文件后缀名
string filetype = filename.Substring(filename.LastIndexOf(".") + 1);
//上传的当前时间作为文件名
string newFileName = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString() + "." + filetype;
string filePath = Server.MapPath("../Upload") + "\\" + newFileName;
FileUpload1.SaveAs(filePath);
BProjectAttachRule.InsertBProjectAttachData(txtHID, newFileName, filePath, System.DateTime.Now, txtCategory.Text, "文档", 1);
Label5.Text = "文档上传成功!";
txtCategory.Text = "";
GetDateGridBProjectInformationAsset();
}
}
catch (Exception ex)
{
Label5.Text = "发生错误:" + ex.Message.ToString();
divGridInformationAsset.Style["Display"] = "Block";
}
}
else
{
Label5.Text = "没有选择要上传的文件!";
divGridInformationAsset.Style["Display"] = "Block";
}
下载代码
string fileName = e.CommandArgument.ToString();
string filePath = Server.MapPath("../Upload/" + e.CommandArgument.ToString());
if (File.Exists(filePath))
{
//以字符流的形式下载文件
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();
}
else
{
Page.RegisterStartupScript("ServiceManHistoryButtonClick", "<script>alert('服务器不存在该附件!');</script>");
}