在使用Flask下载文件时,可以通过以下方式来避免下载重复文件:
import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/download/<filename>")
def download_file(filename):
# 检查文件是否存在
if os.path.exists(filename):
return send_file(filename, as_attachment=True)
else:
return "文件不存在"
if __name__ == "__main__":
app.run()
在上述示例中,使用了os.path.exists
方法来检查文件是否存在,如果文件存在,则使用send_file
方法将文件作为附件进行下载,否则返回一个错误提示。
function downloadFile(filename) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', '/download/' + filename, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
// 文件存在,进行下载
window.location.href = '/download/' + filename;
} else {
// 文件不存在,给出错误提示
alert('文件不存在');
}
}
};
xhr.send();
}
在上述示例中,使用了XMLHttpRequest对象发送一个HEAD请求来检查文件是否存在,如果文件存在,则通过window.location.href
来进行下载,否则给出一个错误提示。
通过上述方法,可以在Flask应用中实现下载文件时的重复文件避免。
领取专属 10元无门槛券
手把手带您无忧上云