如何将这两个项目组合起来(no-dropzone.js):
我只想上传图片文件(pnp,jpg等)
项目1:
的index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>File upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
upload.php的的
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
// File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
// Work out the file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('txt', 'jpg');
if(in_array($file_ext, $allowed)) {
if($file_error === 0) {
if($file_size <= 2097152) {
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if(move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
}
}
}
}
}
?>
与
项目2
的index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drag & Drop Uploading</title>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop files here to upload</div>
<script>
(function() {
var dropzone = document.getElementById('dropzone');
var displayUploads = function(data) {
var uploads = document.getElementById('uploads'),
anchor,
x;
for(x = 0; x < data.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = data[x].file;
anchor.innerText = data[x].name;
uploads.appendChild(anchor);
}
};
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x = 0; x < files.length; x = x + 1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post', 'upload.php');
xhr.send(formData);
};
dropzone.ondrop = function(e) {
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
};
dropzone.ondragover = function() {
this.className = 'dropzone dragover'
return false;
};
dropzone.ondragleave = function() {
this.className = 'dropzone';
return false;
};
}());
</script>
</body>
</html>
upload.php的的
<?php
header('Content-Type: application/json');
$uploaded = array();
if(!empty($_FILES['file']['name'][0])) {
foreach($_FILES['file']['name'] as $position => $name) {
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/' . $name)) {
$uploaded[] = array(
'name' => $name,
'file' => 'uploads/' . $name
);
}
}
}
echo json_encode($uploaded);
?>