[英]How to send http request using XMLHttpRequest instead of form request for Dropzone?
I want to upload files from my computer to the server using DropzoneJS. 我想使用DropzoneJS将文件从计算机上载到服务器。 The documentation says to use a form which includes a URL to post to.
该文档说要使用包含要发布到的URL的表单。 However, instead of this I want to get the files in my javascript file so that I can send a XMLHttpRequest to the server and get a response from the same post.
但是,相反,我想获取我的javascript文件中的文件,以便可以将XMLHttpRequest发送到服务器并从同一帖子中获取响应。 The problem is for some reason the Dropzone needs a URL (Even when I put
问题是由于某些原因,Dropzone需要一个URL(即使我放了
Dropzone.autoDiscover = false;
in my Javascript file with the URL, the error is gone but the dropzone isn't able to function). 在带有URL的Javascript文件中,错误消失了,但dropzone无法运行)。 Is there a way to not put the form action url altogether?
有没有办法不完全将表单操作的URL放在一起? I do not want to make two different http requests.
我不想发出两个不同的http请求。 Here's the form:
形式如下:
<form method="post" enctype="multipart/form-data" id="my-awesome-dropzone" class="dropzone"></form>
Since ie10, it's possible to upload files using XHR2, like this: 从ie10开始,可以使用XHR2上传文件,如下所示:
if (new XMLHttpRequest().upload) {
var form = document.getElementById('my-awesome-dropzone');
var fileSelect = document.getElementById('file-select');
var uploadButton = document.getElementById('upload-button');
form.onsubmit = function(event) {
event.preventDefault();
// Update button text.
uploadButton.innerHTML = 'Uploading...';
// Get the selected files from the input.
var files = fileSelect.files;
// Create a new FormData object.
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// Set up the request.
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
uploadButton.innerHTML = 'Done';
var data = xhr.responseText
// do something with the response
} else {
console.log('An error occurred!');
}
}
xhr.onerror = function() {
console.log('An error occurred!');
}
xhr.send(formData);
}
} else {
// browser doesn't support JS file uploading
}
Source: http://blog.teamtreehouse.com/uploading-files-ajax 来源: http : //blog.teamtreehouse.com/uploading-files-ajax
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.