【发布时间】:2020-02-28 09:07:27
【问题描述】:
我创建了一个按钮,使用后台 JS 表单将图片文件上传到后端。 我确实具有单击图片按钮打开表单以上传图片的功能。 我用找到here 的 cat.jpg 进行了尝试。 我在后端使用烧瓶来检查它是否是批准的类型,然后将其上传到静态文件夹。我添加了一个简单的 print 语句,以查看该方法是否被调用。
看来我的问题在于 addEventListener 提交功能。它似乎没有被调用。我假设因为我没有使用表单制作提交按钮,这就是它没有被调用的原因。但是,输入引发了计算机天真,文件上传有自己的提交,所以我觉得在这种情况下应该正确调用提交函数。我可以得到任何指针,我对 JS 和 Ajax 很陌生!
我的 JS 代码:
document.getElementById('button-picture').addEventListener('click', function() {
// Create a form to upload the picture behind the scenes
var picture_form = document.createElement('form');
picture_form.setAttribute('id', 'image_upload_form');
picture_form.setAttribute('enctype', 'multipart/form-data');
picture_form.setAttribute('method', 'POST');
var input_tag = document.createElement('input');
input_tag.setAttribute('type', 'file');
input_tag.setAttribute('id', 'file_upload');
input_tag.setAttribute('name', 'files');
input_tag.setAttribute('multiple', true);
picture_form.append(input_tag);
// Upload the picture to the backend when it is submitted.
picture_form.addEventListener("submit", function(e) {
// Do I need this?
e.preventDefault();
var request = new XMLHttpRequest();
request.open('POST', '/upload-images', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('ProcessData', false)
var csrf_token = "{{ csrf_token() }}";
request.setRequestHeader('X-CSRFToken', csrf_token);
var form_data = new FormData(picture_form.input.files);
request.send(form_data);
});
input_tag.click()
// Add markup Code to display it.
}, false);
我的后端代码查看此 SO question 中提供的内容。 此外,更新代码以反映此 SO question 无济于事。
更新**,更改代码:
// Create a form to upload the picture behind the scenes
var picture_form = document.createElement('form');
picture_form.setAttribute('id', 'image_upload_form');
picture_form.setAttribute('enctype', 'multipart/form-data');
picture_form.setAttribute('method', 'POST');
var input_tag = document.createElement('input');
input_tag.setAttribute('type', 'file');
input_tag.setAttribute('id', 'file_upload');
input_tag.setAttribute('name', 'files');
input_tag.setAttribute('multiple', true);
picture_form.append(input_tag);
var submit_event = new Event('submit');
picture_form.dispatchEvent(submit_event);
// Upload the picture to the backend when it is submitted.
picture_form.addEventListener("submit", function(e) {
alert("Hello");
// Do I need this?
// e.preventDefault();
var request = new XMLHttpRequest();
request.open('POST', '/upload_images', true);
var csrf_token = "{{ csrf_token() }}";
request.setRequestHeader('X-CSRFToken', csrf_token);
var form_data = new FormData(picture_form);
request.send(form_data);
});
input_tag.click()
【问题讨论】:
-
使用隐藏表单向后端发送数据的动机是什么?
-
适用于文章类型的编辑器,通过在编辑器中按图片按钮插入图片,无需重新加载页面或单独上传图片。
标签: javascript ajax flask