Django网站中文件下载的实现和网页部分打印的实现。

来源:互联网 发布:php判断变量是否设置 编辑:程序博客网 时间:2024/04/30 15:30

先说第一个功能文件下载,

Django的HttpResponse直接就能提供下载,所以我们只要打开一个文件,让HttpResponse返回就好了

f=open("test.txt",'r')a=f.read()f.close()response=HttpResponse(a)return response

有的文件比较大,像上面那样甚至有可能将系统搞崩溃,没关系,可以像下面这样

def readFile(fn, buf_size=262144):        f = open(fn, "rb")        while True:            c = f.read(buf_size)            if c:                yield c            else:                break        f.close()    file_name = "big_file.txt"    response = HttpResponse(readFile(file_name))    return response

关于yield的用法参见http://www.cnblogs.com/tqsummer/archive/2010/12/27/1917927.html

有的时候上面这样只能展示出来,不能激活浏览器的下载,这需要做一个激活。

在上面return response前面加上这两行代码,

response['Content-Type'] = 'application/octet-stream'response['Content-Disposition'] = 'attachment;filename="{0}"'.format(file_name)


关于页面打印

直接上代码吧,简单粗暴。

<html>
<head>
<script language="javascript">
function printdiv(printpage)
{
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
</script>
<title>div print</title>
</head>

<body>
//HTML Page
//Other content you wouldn't like to print
<input name="b_print" type="button" class="ipt"   onClick="printdiv('div_print');" value=" Print ">

<div id="div_print">

<h1 style="Color:Red">The Div content which you want to print</h1>

</div>
//Other content you wouldn't like to print
//Other content you wouldn't like to print
</body>

</html>


0 0