我想使用DropzoneJS将文件从我的电脑上传到服务器。文档说要使用包含要发布到的URL的表单。但是,我想在我的javascript文件中获取文件,以便我可以将XMLHttpRequest发送到服务器并从同一帖子获取响应。问题是由于某些原因Dropzone需要一个URL(即使我把
Dropzone.autoDiscover = false;
在我的带有URL的Javascript文件中,错误消失但dropzone无法运行)。有没有办法不完全放置表单操作URL?我不想做两个不同的http请求。这是以下形式:
<form method="post" enctype="multipart/form-data" id="my-awesome-dropzone" class="dropzone"></form>
答案 0 :(得分:0)
从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
}