我做了一个简单的拖放应用程序,它将您丢弃的文件(图像)发送到PHP文件,该文件检查文件并上传所有内容。我将带有变量的对象发送到PHP,而PHP得到了对象,但不是文件。我已经尝试了几次Google搜索和调整我的代码,但我无法上传给我的文件。
这是我的JavaScript代码:
var DropField = document.getElementById("prof_upload_field")
resDiv = document.getElementById("prof_upl_res_field")
formData = new FormData(),
xhr = new XMLHttpRequest();
// Add class to dropblock when item is dragged over document
document.ondragover = function(){
// Add "dragover" class to dropblock
DropField.className = 'dragOver';
DropField.innerHTML = 'Drop here!';
}
// When something is dropped
DropField.ondrop = function(e){
console.log('Something has been dropped!');
e.preventDefault();
// Get file from drop
var files = e.dataTransfer.files,
// Object to fill
object = {};
// Fill object with values from file
object = {
fileName: files[0].name,
fileSize: files[0].size,
fileType: files[0].type,
}
if(files.length > 1){
resDiv.innerHTML = 'You can only select 1 file!';
throw('You can't upload more than 1 profile picture!');
}
var fileData = JSON.stringify(object);
formData.append('file', files[0]);
formData.append('filedata', fileData);
xhr.open("POST", "ajax/upload.php", true);
xhr.send(formData);
xhr.onload = function(){
resDiv.innerHTML = xhr.responseText;
}
console.log(object);
}
// When something is dragged into the dropblock
DropField.ondragover = function(){
console.log('Something is dragged in the dropblock!');
// Return false to allow a file begin dropped
return false;
}
// When the cursor has left the dropblock
DropField.ondragleave = function(){
console.log('Cursor left the dropblock!');
// Return false to allow a file begin dropped
return false;
}
当我执行print_r($ _ POST)时,它会显示我发送的对象,但不显示该文件。我在这里有一个JSFiddle: