某些时候可能有这样的需求,在网页中点击一个链接或者一个按钮希望返回一张图片、一个pdf文档、一个csv文档等而非HTML。在diango中很容易做到这些。django中的view用来接收http request并返回web response。通常情况下,返回的内容为HTML,但其能够返回的不仅仅如此,还可以是上述图片、pdf文件等等。返回非HTML形式的内容的关键在于HttpResponse这个类,尤其是mimetype这个参数,通过将此参数设置为不同的值可以提示浏览器view返回了不同格式的内容。比如,想要返回图片内容,只需读如一张图片,然后在HttpResponse中指明图片的mimetype并将图片内容作为另一参数response给浏览器,浏览器能够自动正确的显示图片内容。
from django.http import HttpResponsedef my_image(request): image_data = open("/path/to/my/image.png", "rb").read() return HttpResponse(image_data, mimetype="image/png")
import csvfrom django.http import HttpResponse# Number of unruly passengers each year 1995 - 2005. In a real application# this would likely come from a database or some other back-end data store.UNRULY_PASSENGERS = [146,184,235,200,226,251,299,273,281,304,203]def unruly_passengers_csv(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(mimetype='text/csv') response['Content-Disposition'] = 'attachment; filename=unruly.csv' # Create the CSV writer using the HttpResponse as the "file." writer = csv.writer(response) writer.writerow(['Year', 'Unruly Airline Passengers']) for (year, num) in zip(range(1995, 2006), UNRULY_PASSENGERS): writer.writerow([year, num]) return response
from reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hello.pdf' # Create the PDF object, using the response object as its "file." p = canvas.Canvas(response) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() return response
from cStringIO import StringIOfrom reportlab.pdfgen import canvasfrom django.http import HttpResponsedef hello_pdf(request): # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(mimetype='application/pdf') response['Content-Disposition'] = 'attachment; filename=hello.pdf' temp = StringIO() # Create the PDF object, using the StringIO object as its "file." p = canvas.Canvas(temp) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly. p.showPage() p.save() # Get the value of the StringIO buffer and write it to the response. response.write(temp.getvalue()) return response
from django.http import HttpResponseimport xlwtdef viewXls(request): response = HttpResponse(mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=request.xls' book = xlwt.Workbook(encoding='utf8') sheet = book.add_sheet('untitled') for row, column, value in ((0,0,1),(0,1,2),(1,0,3),(1,1,4)) sheet.write(int(row),int(column),value) book.save(response) return response
$.ajax({ url:"{% url 'mycitsm.views.viewXls' %}", data:postData, type:"POST", success:function(result){ }, });//是不可以的,而要使用如下的表单提交才可以:var form = $("#xlsForm");form.attr({ action:"{% url 'mycitsm.views.returnXls' %}", method:"POST" });form.submit();