1. 程式人生 > >Django網站中檔案下載的實現和網頁部分列印的實現。

Django網站中檔案下載的實現和網頁部分列印的實現。

先說第一個功能檔案下載,

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>