常遇到上传下载的功能,这里把我习惯的用法写下来:
上传:
string fileName = "";
fileName = this.fu_pic.FileName;
if (string.IsNullOrEmpty(fileName))
isPic = "0";
else
isPic = "1";
//附件不为空的时候上传图片,否则不处理
if (isPic == "1")
{
byte[] arrayByte = this.fu_pic.FileBytes;
if (arrayByte.Length <= 0)
{
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('上传图片是空文件!')</script>");
AlertMessage("上传图片是空文件!");
this.fu_pic.Focus();
return;
}
string extention = fileName.Substring(fileName.LastIndexOf(".") + 1);
if (extention.ToUpper() != "JPG"
&& extention.ToUpper() != "BMP"
&& extention.ToUpper() != "PNG"
&& extention.ToUpper() != "GIF")
{
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片格式错误,请上传jpg/bmp/png/gif格式图片!')</script>");
AlertMessage(@"图片格式错误,请上传jpg/bmp/png/gif格式图片!");
this.fu_pic.Focus();
return;
}
else
{
//按照年/月 生成文件目录
fileName = string.Format(@"UploadImage\{0}\{3}\{1}{2}", DateTime.Now.Year.ToString(), DateTime.Now.ToString("yyyyMMddHHmmssfff"), fileName, DateTime.Now.Month.ToString());
//获取附件上传物理路径(这里设置在config文件中)
string dePath = ConfigurationManager.AppSettings["upload"].ToString();
string filePath = Path.Combine(dePath, fileName);//Server.MapPath(@".." + fileName);//外面一层就是网站目录
if (saveView(arrayByte, filePath))
{
//saveAttach = true;
}
else
{
//saveAttach = false;
//Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('图片上传服务器失败!')</script>");
AlertMessage("图片上传服务器失败!");
this.fu_pic.Focus();
return;
}
}
}
public bool saveView(byte[] arry_byte, string filePath)
{
bool rst = false;
FileStream saveStream = null;
try
{
//判断文件夹是否存在
FileInfo file = new FileInfo(filePath);
if (!file.Exists)
{
if (!Directory.Exists(file.DirectoryName))
Directory.CreateDirectory(file.DirectoryName);
}
file = null;
//保存文件
saveStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
saveStream.Write(arry_byte, 0, arry_byte.Length);
saveStream.Close();
rst = true;
}
catch (Exception)
{
rst = false;
}
return rst;
}
下载保存:
/// <summary>
/// 下载服务端文件
/// </summary>
/// <param name="fileName">下载时客户端显示名称</param>
/// <param name="filePath">服务端文件完全物理路径</param>
/// <returns></returns>
public void DownloadFile(string fileName, string filePath)
{
//服务端文件是否存在
if (File.Exists(filePath))
{
FileInfo fi = new FileInfo(filePath);
long length = fi.Length;
//读取文件到流sr中,using为防止文件被进程占据,强制释放资源
using (FileStream sr = new FileStream(filePath, FileMode.Open))
{
int startlength = 0;
int bufferSize = 1;
byte[] buffer = new byte[bufferSize];
byte[] allBuffer = new byte[length];
//循环读取流到allBuffer中
while (startlength < length)
{
//读取bytes个字节到buff中的0到bufferSize位置
//sr.read后,sr自动移动到读取的位置
int bytes = sr.Read(buffer, 0, bufferSize);
//将buff内容存入allBuffer中
allBuffer[startlength] = buffer[0];
//前进bytes个位置
startlength += bytes;
}
//清空缓存中的流
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
//输出流
Response.AddHeader("Accept-Ranges", "bytes");
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("gb2312")));
Response.BinaryWrite(allBuffer);
Response.Flush();
Response.End();
}
}
}
更加简洁的下载:
string fileName = "日志.txt";
string txtFullFilePath = "c:/test/aa.txt";
if (File.Exists(Server.MapPath(txtFullFilePath)))
{
//文件对象
FileInfo fileInfo = new FileInfo(Server.MapPath(txtFullFilePath));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentType = "application/octet-stream";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
}
来源:https://www.cnblogs.com/maomaokuaile/p/3503176.html