首页 > 解决方案 > django:如何正确指定输出下载文件类型(在本例中为 mp3)?

问题描述

我有一个简单的 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,它包含“无”。

标签: djangotext-to-speech

解决方案


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

我已经设法以这种方式正确返回 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

推荐阅读