问题描述
我为此使用了 Flask 和 javascript。我能够使用对服务器的 ajax 调用下载用户请求的音频文件,并且可以将其从 webm 转换为 mp3,但是在将其从我的计算机发送回网络应用程序时,音频文件被损坏。这是我的代码
$(document).ready(function() {
$('#download').click(function(event) {
$.ajax({
data : {
name:"1",url : player.getVideoUrl(),title: document.getElementById("songTitle").innerHTML,},type : 'POST',url : '/play',})
.done(function(data){
console.log(data);
const a = document.createElement("a");
a.style.display = "none";
document.body.appendChild(a);
var type="audio/mpeg"
// Set the HREF to a Blob representation of the data to be downloaded
a.href = window.URL.createObjectURL(
new Blob([data],{ type })
);
// Use download attribute to set set desired file name
a.setAttribute("download",document.getElementById("songTitle").innerHTML );
// Trigger the download by simulating click
a.click();
// Cleanup
window.URL.revokeObjectURL(a.href);
document.body.removeChild(a);
});
event.preventDefault();
});
});
这是我的 application.py 文件中的代码,用于发回音频文件
@app.route('/play',methods=["GET","POST"])
def e():
if request.method == "POST":
if request.form['name']=="1":
attempted_url = request.form["url"]
if attempted_url != "":
result_id = get_media(attempted_url)
session["url"] = attempted_url
session["id"] = result_id
filename = request.form["title"]
session["filename"] = filename
return redirect(url_for("return_file"))
else:
#this is a different set of code which returns data for a searched name
data = yt_cal(request.form['name'])
return jsonify(data = data)
elif len(temp)==1 and k[0] == 0:
k[0] = 1
for data in finaldata[0]:
if data['id'] == int(temp[0]):
temp2 = data
return render_template("play.html",data = temp2)
@app.route("/return-file/")
def return_file():
filename = session.get("filename")
filename_formatted = filename + ".mp3"
downloads/{}.mp3".format(session.get("id"))
location = "media/Audio downloads/{}.mp3".format(session.get("id"))
return send_file(
location,attachment_filename=filename_formatted,as_attachment=True
)
该文件已下载到网页上,但是当我尝试在计算机上再次打开它时,它会引发 0xc00d36c4 错误。在将下载的 mp3 文件发送到网络应用程序之前,我已经检查过它是否有效,并且确实如此,介于两者之间的某个地方已损坏。此外,我尝试将 contentType: "audio/mpeg" 添加到 ajax 请求,但随后在 ajax 调用中返回 400。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)