C#实现word文件下载的代码
效果:
思路:
简单的有两种方式下载,一种是流下载,一种是writefile下载。以下是使用writefile下载。
代码:
protected void linkbutton1_click(object sender, eventargs e)
{
try
{
//writefile实现下载(word)
string filename = "qingpingguo.docx";//客户端保存的文件名
string filepath = server.mappath("~\\excel\\" + tb1.text);//路径
fileinfo fileinfo = new fileinfo(filepath);
response.clear();
response.clearcontent();
response.clearheaders();
response.addheader("content-disposition", "attachment;filename=" + 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();
}
catch (exception ex)
{
response.write(ex.message);
}
/*************以下为流方式下载****************/
//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();
}
上一篇: python数据清洗系列之字符串处理详解
下一篇: asp.net发送邮件实现方法