django:如何正确指定输出下载文件类型(在本例中为mp3)?

时间:2018-05-29 17:02:48

标签: django text-to-speech

我有一个简单的django平台,我可以上传文本文件。最后,我想返回一个可下载的mp3音频文件,该文件由上传文件中的文本组成。我目前的问题是我似乎无法正确指定网站输出以供下载的文件类型。

然后我尝试将网站的可下载输出设为mp3文件:

views.py(代码改编自https://github.com/sibtc/simple-file-upload

def simple_upload(request):
if request.method == 'POST' and request.FILES['myfile']:
    myfile = request.FILES['myfile']
    print(str(request.FILES['myfile']))
    x=str(myfile.read())
    tts = gTTS(text=x, lang='en')
    response=HttpResponse(tts.save("result.mp3"),content_type='mp3')
    response['Content-Disposition'] = 'attachment;filename=result.mp3'
    return response
return render(request, 'core/simple_upload.html')

按下上传按钮后,文字转语音转换成功,但响应的content_type无法定义为' mp3'。下载产生的文件为result.mp3.txt,其中包含'无'。

2 个答案:

答案 0 :(得分:1)

您可以尝试使用下面的示例代码准备您的回复吗?

我已设法以这种方式正确返回CSV文件,因此它也可能对您有帮助。

这是:

HttpResponse(content_type='text/plain')  # Plain text file type
response['Content-Disposition'] = 'attachment; filename="attachment.txt"'  # Plain text file extension
response.write("Hello, this is the file contents.")
return response

答案 1 :(得分:0)

我可以在这里看到两个问题。第一个是tts.save()返回None,然后直接传递给HttpResponse。其次,content_type设置为mp3,应该设置为audio/mp3

致电tts.save()后,打开mp3并将文件句柄传递给HttpResponse,然后正确设置content_type - 例如:

def simple_upload(request):
    if request.method == 'POST' and request.FILES['myfile']:
        ...
        tts.save("result.mp3")
        response=HttpResponse(open("result.mp3", "rb"), content_type='audio/mp3')