장고 문서를 살펴본 결과 파일을 첨부 파일로 렌더링 할 수있는이 코드를 찾았습니다.
dl = loader.get_template('files/foo.zip')
context = RequestContext(request)
response = HttpResponse(dl.render(context), content_type = 'application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response
foo.zip 파일은 pythons zipfile.ZipFile (). writestr 메서드를 사용하여 생성되었습니다.
zip = zipfile.ZipFile('foo.zip', 'a', zipfile.ZIP_DEFLATED)
zipinfo = zipfile.ZipInfo('helloworld.txt', date_time=time.localtime(time.time()))
zipinfo.create_system = 1
zip.writestr(zipinfo, StringIO.StringIO('helloworld').getvalue())
zip.close()
하지만 파일을 렌더링하기 위해 위의 코드를 시도했을 때이 오류가 발생했습니다.
'utf8'코덱이 위치 10의 0x89 바이트를 디코딩 할 수 없음 : 잘못된 시작 바이트
이 작업을 올바르게 수행하는 방법에 대한 제안이 있습니까?
여러분이 원하는 것은 사람들이 다운로드 할 수 있도록 파일을 제공하는 것입니다. 그렇다면 파일을 렌더링 할 필요가 없습니다. 템플릿이 아닙니다. Django의 HttpResponse를 사용하여 첨부 파일 로 제공하면됩니다 .
zip_file = open(path_to_file, 'r')
response = HttpResponse(zip_file, content_type='application/force-download')
response['Content-Disposition'] = 'attachment; filename="%s"' % 'foo.zip'
return response
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다