gpt4 book ai didi

javascript - 将数据从 Python (Flask) 发送到 Javascript?

转载 作者:行者123 更新时间:2023-11-30 12:49:33 47 4
gpt4 key购买 nike

我正在尝试在我的网站上实现拖放文件 uploader 。文件被删除后立即上传,我想生成一个带有 flask 的 URL,它将在预览下弹出。我正在使用 dropzone.js。在 dropzone 的文档中,提供了一个示例作为指南,用于从服务器发送回数据以在文件上传后显示。 https://github.com/enyo/dropzone/wiki/FAQ#i-want-to-display-additional-information-after-a-file-uploaded

但是,当我尝试在创建 dropzone 的 Jinja 模板中的内联 Javascript 中使用 url_for 时,我得到了一个看起来像/%7Bfilename%7D 的链接只是为了确保我在其中为 URL 弹出了一个快速打印语句,它在控制台中正常显示。

我的 python uploader :

def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
if is_image(file.filename): # generates a shortened UUID name for the image
filename = shortuuid.uuid()[:7] + "." + file.filename.rsplit(".", 1)[1]
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

@app.route ('/<filename>')
def uploaded_image(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

以及我的 index.html 模板中的内联 JS:

<script>
var mydropzone = new Dropzone(document.body, {
url: "{{url_for('upload_file')}}",
previewsContainer: "#previews",
clickable: "#clickable",
init: function() {
this.on("success", function(file, responseText) {
var responseText = " {{ url_for('uploaded_image', filename='{filename}')}} ";
var span = document.createElement('span');
span.setAttribute("style", "position: absolute; bottom: -50px; left: 3px; height: 28px; line-height: 28px; ")
span.innerHTML = responseText;
file.previewTemplate.appendChild(span);

});
}


});

我是否遗漏了一些基本的东西?我是否需要使用像 JSON/Ajax 这样的东西(从来没有使用过这些,但谷歌搜索总是提出它们),因为 URL 是从服务器发回的数据?

最佳答案

简单地:

  1. 返回文件路径给客户端:

    def upload_file():
    if request.method == 'POST':
    # ... snip ...
    return url_for('uploaded_image', filename=filename)
  2. 删除 on('success') 函数中的 var responseText 行,因为您将在响应中返回 URL。

关于javascript - 将数据从 Python (Flask) 发送到 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21439807/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com