【问题标题】:HTML Flask Page not reloading using fetch()HTML Flask 页面不使用 fetch() 重新加载
【发布时间】:2022-12-31 01:28:21
【问题描述】:

我正在编写一个应用程序来将目标文件上传到存储桶。该应用程序能够浏览文件并使用按钮提交文件,从而成功上传文件。问题是,我必须重新加载页面才能在屏幕上看到新文件并清除“已浏览”文件选择。我通常使用以下后置函数,但它不适用于文件选择。我发现 fetch() 方法对此很有帮助,但发现了上述问题。

帮助解决任何一个问题都会很棒。由于某种原因,我的 post() 函数无法处理文件,我无法在提交到“/uploadToBucket”后执行 request.files['thisFile']。获取帖子有效,但我需要手动或使用“window.location = window.location.href;”刷新页面这会导致其他问题。

function upload(bucket) {
  const selectedFile = document.getElementById('bucketUpload').files[0];
  let formData = new FormData();
     
  formData.append("thisFile", selectedFile);
  formData.append("bucket", bucket);

  fetch('/uploadToBucket', {method: "POST", body: formData});
  
  // fetch('/uploadToBucket', {
  //   method: "POST",
  //   body: formData
  // }).then(() => {
  //   window.location = window.location.href;
  // })

  // parameters = {
  //   bucket: bucket,
  //   thisFile: selectedFile,
  // }
  // post("/uploadToBucket", parameters);
}

这是我的帖子()

function post(path, params, method='post') {
    // The rest of this code assumes you are not using a library.
    // It can be made less verbose if you use one.
    const form = document.createElement('form');
    form.method = method;
    form.action = path;

    for (const key in params) {
    if (params.hasOwnProperty(key)) {
        const hiddenField = document.createElement('input');
        hiddenField.type = 'hidden';
        hiddenField.name = key;
        hiddenField.value = params[key];

        form.appendChild(hiddenField);
    }
    }
    document.body.appendChild(form);
    form.submit();
}

谢谢

【问题讨论】:

  • 我很确定需要fetch因为它不会刷新页面。您可能需要使用表格?
  • @evolutionxbox 我在获取之前尝试过,您可以看到注释掉的参数和 post("/uploadToBucket", parameters)。当我尝试该方法时,执行 content = request.files.get('thisFile', None) 总是返回 None。

标签: javascript html


【解决方案1】:

fetch 提供了一个API,用于在某个任务完成时从后端获取响应。在你的例子中:

// Front end
fetch('/uploadToBucket', {method: "POST", body: formData})
   .then((response) => { 
      // update the page to view the file and clear form fields //
      let myForm = document.getElementById('my-form');
      myForm.reset();
});

// Back end
def view(request):
    # upload document with the mechanism you have in place #
    all_files = ... # query all your files after the upload #
    return HttpResponse(all_files)

这会给你一个前进的方向吗?

【讨论】:

    猜你喜欢
    • 2021-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-19
    • 2021-10-29
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多