2

当我打开使用以下代码生成的文本文件附件时,HTTP 响应似乎总是从每一行中删除 CR,该文件的用户将使用记事本,因此我需要在每一行上使用 CR/LF。

the_file = tempfile.TemporaryFile(mode='w+b') 
<procedure call to generate lines of text in "the_file">
the_file.seek(0)
filestring = the_file.read()
response = HttpResponse(filestring,
    mimetype="text/plain")
response['Content-Length'] = the_file.tell()
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"' 
return response

如果我使用这种方法,我会在我的文件中得到 CR/LF,但我想完全避免将文件写入磁盘,所以这似乎不是一个好的解决方案:

the_file = open('myfile.txt','w+')
<procedure call to generate lines of text in "the_file">
the_file.close
the_file = open('myfile.txt','rb')
filestring = the_file.read()
response = HttpResponse(filestring,
    mimetype="text/plain")
response['Content-Length'] = the_file.tell()
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"' 
return response

我觉得解决方案应该很明显。但我无法关闭临时文件并以二进制模式重新打开它(保留 CR/LR)。哎呀,我什至不确定我是否在正确的范围内如何正确执行此操作:) 尽管如此,我想在组装配置后将此数据作为附件传递给用户并让它正确显示在记事本中。tempfile 是这里的错误解决方案,还是有一种 tempfile 机制可以为我解决这个问题,而无需在磁盘上使用文件 IO。

4

1 回答 1

1

而不是使用TemporaryFile,只需使用HttpResponse

response = HttpResponse('', content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename="4cos_example.txt"'
response.write('first line\r\n')
response.write('second line\r\n')    
return response

仅供参考,如果这是一个非常大的响应,您也可以使用StreamingHttpResponse. 但只有在需要时才这样做,因为像这样的标题Content-Length将无法自动添加。

于 2013-11-02T16:33:10.230 回答