django - 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
,它包含“无”。
解决方案
您可以尝试使用下面的示例代码准备您的回复吗?
我已经设法以这种方式正确返回 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
推荐阅读
- jquery - 在 MS Team 站点中自定义调查问题样式
- javascript - 程序停止后不停止运行的 setTimeout 的替代方案?
- python - django-elasticsearch-dsl:如何添加脚本进行过滤?
- c# - 在 LINQ 中选择 DISTINCT LEFT([string],2)
- java - 如何仅使用命令行创建工件 jar?
- swift - 如何在swift中禁用anyObject按钮中的按钮
- php - 使用数组 wordpress php 更改元数据的批量页面克隆
- javascript - 我正在尝试在 Webflow 中嵌入交互式图像,但内容中的换行符未显示
- flutter - 终止飞镖/颤振中的功能
- mysql - 如何根据选择查询删除