当我打开使用以下代码生成的文本文件附件时,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。
请您参考如下方法:
不使用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 这样的 header 将无法自动添加。
