drag & drop (and choose file) uploading - javascript

How can I combine these two projects like this(no-dropzone.js):
I want only image file uploading (pnp, jpg etc.)
Project 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;
}
}
}
}
}
?>
with
Project 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);
?>

Related

Uncaught Syntax Error: Unexpected end of input Javascript

I want to learn JavaScript and I tried to created a multiple Ajax uploader. I encountered this error:
In Google Chrome :
Uncaught SyntaxError: Unexpected end of input,
In Mozilla Firebug
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
uploaded = JSON.parse(this.response);
And my JavaScript file
var app = app || {};
(function(o) {
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);//this is where error occurs
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event) {
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for (i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function(value) {
if (o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if (o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if (o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
};
}(app));
my Php file
<?php
header('Content-Type:application/json');
$uploaded = [];
$allowed = ['MP4','PNG','JPG'];
$succeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if ($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeded[] = array(
'name' => $name,
'file' => $file
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded' => $succeded,
'failed' => $failed
));
}
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset ="UTF-8"/>
<title>Ajax Uploader</title>
<link rel="stylesheet" href="global.css"/>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id ="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
</form>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload.php',
finished: function(data) {
var uploads = document.getElementById('upload'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if (data.failed.length) {
failed.innerHTML = '<p>Unfortunately, the following is an error:</p>';
}
uploads.innerText = '';
for (x = 0;x < data.succeeded.length;x= x + 1) {
anchor = document.createElement('a');
anchor.href ='uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for (x = 0; x < data.failed.length; x = x + 1) {
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function() {
console.log('not working');
}
});
});
</script>
Any Ideas?

AJAX Upload Web App

I need some assistance please.
I am trying to create an ajax upload web app from scratch as a personal hobby.
I was able to get the files to upload to my uploads folder successfully, but I just can't seem to get the uploaded links to appear under the upload box and stay there permanently even after refreshing the web page.
I keep getting this error message in the google chrome browser console: Uncaught TypeError: Cannot read property 'length' of undefinedand it is pointing me to this line in the index.php:for(x = 0; x < data.succeeded.length; x = x + 1) {
Also the google chrome console is marking this as (anonymous function) in the upload.js file:o.options.finished(uploaded);
I had used some youtube videos as a guide, but I just can't seem to figure it out.
Kindly Help Me Please
This is the index.php code and below is the upload.php code also the upload.js code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Uploader</title>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload.php',
finished: function(data) {
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if(data.failed.length) {
failed.innerHTML = '<p>Unfortunately, the following failed:</p>';
}
uploads.innerText = '';
for(x = 0; x < data.succeeded.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x = 0; x < data.failed.length; x = x + 1 ) {
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
upload.appendChild(failed);
},
error: function() {
console.log('Not working');
}
});
});
</script>
</form>
</body>
</html>
Upload.php code
<?php
header('Content-Type: application/json');
$uploaded = '';
$allowed = '';
$succedeed = '';
$failed = '';
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(move_uploaded_file($temp, "uploads/{$file}") === true) {
$succedeed[] = array(
'name' => $name,
'file' => $file
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if(!empty($_POST['ajax'])) {
echo json_encode(array(
'succedeed' => $succedeed,
'failed' => $failed
));
}
}
This is the upload.js code
var app = app || {};
(function(o) {
"use strict";
//Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event) {
var percent;
if(event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
I think the problem is due to if(move_uploaded_file($temp, "uploads/{$file}") === true) try if(move_uploaded_file($temp, "uploads/{$file}") == true)
and also check data.succedeed spell in index.php

how to write to database after javascript client side photo resize and upload

I have found a script online which resizes an image client side and then uploads the image to server. This works fine but what I need is to write the image name to mysql database. I know how to do it, but its not working and I think it has something to do with the fact that the script runs client side.
Can anyone look at the following and see where to put the mysql statement. Or if there is a better way of doing it altogether.
upload-form.php
<script>
function uploadphoto()
{
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
}
function resizeAndUpload(file)
{
var reader = new FileReader();
reader.onloadend = function()
{
var tempImg = new Image();
tempImg.src = reader.result;
tempImg.onload = function()
{
var MAX_WIDTH = 695;
var MAX_HEIGHT = 470;
var tempW = tempImg.width;
var tempH = tempImg.height;
if (tempW > tempH)
{
if (tempW > MAX_WIDTH)
{
tempH *= MAX_WIDTH / tempW;
tempW = MAX_WIDTH;
}
}
else
{
if (tempH > MAX_HEIGHT)
{
tempW *= MAX_HEIGHT / tempH;
tempH = MAX_HEIGHT;
}
}
var canvas = document.createElement('canvas');
canvas.width = tempW;
canvas.height = tempH;
var ctx = canvas.getContext("2d");
ctx.drawImage(this, 0, 0, tempW, tempH);
var dataURL = canvas.toDataURL("image/jpeg");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(ev)
{
document.getElementById('filesInfo').innerHTML = 'Done!';
};
xhr.open('POST', 'upload-resized-photo.php', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data = 'image=' + dataURL;
xhr.send(data);
}
}
reader.readAsDataURL(file);
}
</script>
<form enctype="multipart/form-data" method="post" onsubmit="uploadphoto()">
<div class="row">
<label for="fileToUpload">Select Files to Upload</label><br />
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple="multiple" />
<output id="filesInfo"></output>
</div>
<div class="row">
<input type="submit" value="Upload" />
</div>
</form>
upload-resized-photo.php
<?php
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
// I did have the mysql insert here but it didnt even execute. Think it is due to xhr.open post method.
}
?>
I test the following code on my computer:
if ($_POST)
{
define('UPLOAD_DIR', 'uploads/');
$img = $_POST['image'];
$img = str_replace('data:image/jpeg;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.jpg';
$success = file_put_contents($file, $data);
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO images (image_name)
VALUES ('{$file}')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
check your folder permissions, see the following images (Mysql + Files)
This function check all input[type=file]
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for (var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
you should call that function in:
function uploadphoto(oForm)
{
if(!Validate(oForm)){
return false;
}
if (window.File && window.FileReader && window.FileList && window.Blob)
{
var files = document.getElementById('filesToUpload').files;
for(var i = 0; i < files.length; i++)
{
resizeAndUpload(files[i]);
}
}
else
{
alert('The File APIs are not fully supported in this browser.');
}
return false;
}
and in your form pass the form as parameter:
<form enctype="multipart/form-data" method="post" onsubmit="return uploadphoto(this)">
Good luck

Dragstart event does not fire in firefox

I have a problem with a dragstart event in my javascript. When using chrome it works perfectly fine, but not in firefox, where it wont fire at all.
(function () {
var dropzone = document.getElementById('dropzone-add');
var dropzone2 = document.getElementById('dropzone-del');
var draggedItem;
function drag (e) { //This one does not fire in firefox.. I have tried many methods..
e.dataTransfer.setData('text/plain', e.target.src);
draggedItem = e.target;
}
var displayUploads = function (data) {
var uploads = document.getElementById('uploads');
for(index=0; index<data.length; index=index+1){
var div = document.createElement('div');
var anchor = document.createElement('a');
var image = document.createElement('img');
div.className = 'col-lg-2 col-md-4 col-xs-6 thumb';
anchor.className = 'thumbnail';
anchor.href = '#';
image.className = 'img-responsive';
image.src = data[index].file;
image.alt = data[index].name;
anchor.appendChild(image);
div.appendChild(anchor);
uploads.insertBefore(div, uploads.firstChild);
image.setAttribute('draggable', true);
image.ondragstart = function(event) {drag(event)}; //This is the elment that will be draggable.
//image.addEventListener('dragstart', drag, false);
}
}
var upload = function (files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
index;
for(index=0; index<files.length; index = index+1){
formData.append('file[]', files[index]);
}
xhr.onload = function () {
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post', 'upload.php');
xhr.send(formData);
}
var removeFile = function(src){
xhr = new XMLHttpRequest();
xhr.onload = function () {
var data = this.responseText;
console.log(data);
}
xhr.open('post', 'delete.php');
xhr.send(src);
}
dropzone.ondrop = function (e) {
e.preventDefault();
this.className = 'dropzone';
if(e.dataTransfer.files.length < 1){
alert('Use the other dropzone to delete.');
return false;
}
else
upload(e.dataTransfer.files);
}
dropzone.ondragover = function () {
this.className = 'dropzone dragover';
return false;
}
dropzone.ondragleave = function () {
this.className = 'dropzone';
return false;
}
dropzone2.ondrop = function (e) {
e.preventDefault();
this.className = 'dropzone';
var data = e.dataTransfer.getData('text');
console.log(draggedItem);
console.log(data);
//removeFile(data);
}
dropzone2.ondragover = function () {
this.className = 'dropzone dragover';
return false;
}
}());
The outputed images becomes properly draggable and is working fine in chrome. I have tried to use methods like event.originalEvent without success. Would appreciate any help, I am stuck right now. Please ignore the awfulness in the loop.
On top html
<html>
<head>
<meta charset="utf-8">
<title>Upload - drag drop</title>
<link rel="stylesheet" href="global.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="content-fluid">
<div class="dropzone" id="dropzone-add">Drag the file you want to upload here</div>
<div class="dropzone" id="dropzone-del">Drag the file you want to delete here</div>
<div class="row" id="uploads">
</div>
</div>
Upload.php
<?php
$uploaded = array();
if(!empty($_FILES['file']['name'][0])){
$upload_folder = 'uploads/';
foreach($_FILES['file']['name'] as $position => $name){
$upload_path = $upload_folder . time() . '_' . basename($_FILES['file']['name'][$position]);
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], $upload_path)){
$uploaded[] = array('name' => $name, 'file' => $upload_path);
}
}
echo json_encode($uploaded);
}
?>

Uncaught SyntaxError: Unexpected token < (anonymous function) on console

I am creating an upload file application. I wrote it using AJAX and PHP.
It is working fine on the localhost but when I uploaded it to my web server. It returns the error:
Uncaught SyntaxError: Unexpected token <
It is pointing to the line
uploaded = JSON.parse(this.response);
This line is in my upload.js script file
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if (this.readyState === 4) {
if (this.status === 200) {
uploaded = JSON.parse(this.response);
if (typeof obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
for(i=0; i<source.length; i = i+1){
data.append('file[]',source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function (value){
if (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
Here are the other codes for reference
upload.php
<?php
header('Content-Type: application/JSON');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file'])) {
foreach ($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0){
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() .'.'.$ext;
if (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
and here's my html form
index.php
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload Files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files:f,
progressBar:pb,
progressText:pt,
processor: 'upload.php',
finished: function(data){
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'), anchor, span, x;
if (data.failed.length) {
failed.innerHTML = '<p>The following files failed to upload</p>'
}
uploads.innerText = '' ;
anchor = document.createElement('p');
anchor.innerText = "Upload Completed!";
anchor.target = '_blank';
succeeded.appendChild(anchor);
for(x=0;x<data.failed.length; x=x+1){
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
This code works on the localhost. It is uploading the files to my localhost server and shows the loading progressbar.
But when I deploy this to my web server it shows the progressbar loading slowly until it reaches 100%. But when I look into the uploads directory in my server nothing was uploaded.
you have a missing } at the end of the code in upload.php, before the php end (?>):
'failed' =>$failed
));
}
}
?>

Categories

Resources