我创建了一个按钮,用于使用后台JS表单将图片文件上传到后端。我确实具有单击图片按钮的功能,打开打开表格以上传图片。我用发现的here cat.jpg进行了尝试。我在后端使用flask,该烧瓶检查其是否为批准的类型,然后将其上传到静态文件夹。我添加了一个简单的print语句,以查看该方法是否被调用。
似乎我的问题是与addEventListener提交功能有关。它似乎没有被调用。我假设这是因为我没有使用表单创建提交按钮,所以才不调用它。但是,输入会引起计算机天真的,具有自己的提交的文件上传,因此我觉得在这种情况下应正确调用Submit函数。我可以获取任何指针吗,我对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);
要手动提交表单,您可以使用HTMLFormElement.submit()
方法。但这不会导致表单元素触发HTMLFormElement.submit()
事件。
在这种情况下,您需要创建一个submit
对象并将其分派到表单上。如下。
Event
这将触发Event
事件,并导致事件监听器上的回调被调用。
但是您的代码将在以下行中断:
var picture_form = document.createElement('form');
...
var submitEvent = new Event('submit');
picture_form.dispatchEvent(submitEvent);
submit
构造函数接受一个var form_data = new FormData(picture_form.input.files);
元素作为参数。不是单个输入,因为它是从FormData
元素中提取的键值对的集合。将该行更改为以下内容:
FormData
也应删除您包含的<form>
标头。通过<form>
发送时,<form>
对象将自动设置正确的标题。