django:如何正确指定输出下载文件类型(在本例中为 mp3)?
django: how to correctly specify output-download file-type (in this case mp3)?
我有一个简单的 django 平台,我可以在其中上传文本文件。最后,我想要 return 一个可下载的 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
,它包含 'None'.
您可以尝试使用下面的示例代码准备您的回复吗?
我已经成功地 return 通过这种方式正确生成了 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
这里有两个问题。第一个是 tts.save()
returns 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')
我有一个简单的 django 平台,我可以在其中上传文本文件。最后,我想要 return 一个可下载的 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
,它包含 'None'.
您可以尝试使用下面的示例代码准备您的回复吗?
我已经成功地 return 通过这种方式正确生成了 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
这里有两个问题。第一个是 tts.save()
returns 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')