I copied a code online to upload a large file to my server. It basically cut the large file into chunks and send then end them individually. So the first chunk get successfully sent to the server, but the rest just does not work. I am not sure which stage cause the problem, can someone please help.
<html>
<head>
<title>Upload Files using XMLHttpRequest</title>
<script type="text/javascript">
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
function sendRequest() {
var blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var i =0;
var part = 0;
while( start < SIZE ) {
var chunk = blob.slice(start, BYTES_PER_CHUNK);
//alert(chunk.size());
uploadFile(chunk,part);
//alert("here");
start = start + BYTES_PER_CHUNK;
part++;
}
}
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile(blobFile,part) {
var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php"+"?"+"file="+file.name+"&num=" + part);
xhr.onload = function(e) {
//alert("loaded!");
};
xhr.setRequestHeader('Cache-Control','no-cache');
xhr.send(fd);
return;
//while(xhr.readyState!=4){}
//alert("oen over");
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post" action="upload.php">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
<input type="button" value="cancel" onClick="uploadCanceled();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="sendRequest();" value="Upload" />
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>
the Code on the Server
$target_path = "uploads/";
$tmp_name = $_FILES['fileToUpload']['tmp_name'];
$size = $_FILES['fileToUpload']['size'];
$name = $_FILES['fileToUpload']['name'];
$sports = $_GET['file'];
$part =(string)$_GET['num'];
//$part = split("/\=/", $part);
$target_file = $target_path .$part. $sports;
// Open temp file
$out = fopen($target_file, "wb");
if ( $out ) {
// Read binary input stream and append it to temp file
$in = fopen($tmp_name, "rb");
if ( $in ) {
while ( $buff = fread( $in, 1048576 ) ) {
fwrite($out, $buff);
}
}
fclose($in);
fclose($out);
}
?>
There is a glitch in the code above.
You are calling uploadFile in while loop like this..
while( start < SIZE ) {
var chunk = blob.slice(start, BYTES_PER_CHUNK);
//alert(chunk.size());
uploadFile(chunk,part);
//alert("here");
start = start + BYTES_PER_CHUNK;
part++;
}
You are not waiting for chunk to load successfully !! You keep on uploading the chunks until the end. You can wait for one chunk to upload successfully and then load the next.
I feel you can try the following ..
var blob;
var start;
var part;
var chunk;
const SIZE = blob.size;
var xhr;
function sendRequest() {
blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
start = 0;
part = 0;
xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php"+"?"+"file="+file.name+"&num=" + part);
xhr.onload = function(e) {
//alert("loaded!");
};
xhr.setRequestHeader('Cache-Control','no-cache');
chunk = blob.slice(start, BYTES_PER_CHUNK);
//alert(chunk.size());
uploadFile(chunk,part);
//alert("here");
start = start + BYTES_PER_CHUNK;
part++;
}
function uploadFile(blobFile,part) {
var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
xhr.send(fd);
return;
//while(xhr.readyState!=4){}
//alert("oen over");
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
while( start < SIZE ) {
chunk = blob.slice(start, BYTES_PER_CHUNK);
//alert(chunk.size());
uploadFile(chunk,part);
//alert("here");
start = start + BYTES_PER_CHUNK;
part++;
}
}
The reason that the rest are not uploading is that your slice loop is not right.
change it to the following and you should be golden.
var start = 0;
var end = BYTES_PER_CHUNK;
var part = 0;
while( start < SIZE ) {
var chunk = blob.slice(start, end);
uploadFile(chunk,part);
start = end;
end = start + BYTES_PER_CHUNK;
part++;
}
The .JS script here, uploads the blob in chunks successfully.
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var blob; var blob_1;
var start; var end;
var num; var part;
var SIZE; var size; var fileSize = 0;
var BYTES_PER_CHUNK; var NUM_CHUNKS; var chunk; var chunk_size = 0;
var xhr; var counter = 0;
function sendRequest() {
blob = document.getElementById('file').files[0];
// blob = new Blob(blob_1, {type: 'video/mp4'});
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
var i = 0;
var start = 0;
var end = BYTES_PER_CHUNK;
var part = 0;
var NUM_CHUNKS = Math.max(Math.ceil(SIZE / BYTES_PER_CHUNK), 1);
while( start < SIZE ) {
var chunk = blob.slice(start, end);
uploadFile(chunk,part);
start = end;
end = start + BYTES_PER_CHUNK;
part++; counter++;
}
};
function fileSelected() {
var file = document.getElementById('file').files[0];
if (file) {
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
};
function uploadFile(blobFile,part) {
var file = document.getElementById('file').files[0];
var fd = new FormData();
fd.append("file", blobFile); fd.append("chunk_num", NUM_CHUNKS);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", "uploadhandler.php"+"?"+"filen="+file.name+"&num="+part+"&counter="+counter);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.onload = function(e) {
//alert("loaded!");
};
xhr.setRequestHeader('Cache-Control','no-cache');
xhr.send(fd);
return;
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
document.getElementById('progressBar').style.backgroundColor="teal";
}else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
if( start < SIZE ) {
chunk = blob.slice(start, end);
uploadFile(chunk,part);
start = end;
end = start + BYTES_PER_CHUNK;
part = part + 1;
}
document.getElementById("msgStatus").innerHTML = evt.target.responseText;
//alert("complete");
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
//alert("The upload has been canceled by the user or the browser dropped the connection.");
}
The .PHP code here stores each chunk in the "uploads/" folder
session_start();
$counter = 1;
$_SESSION['counter'] = ($_REQUEST['num'] + 1);
// changing the upload limits
ini_set('upload_max_filesize', '100M');
ini_set('post_max_size', '100M');
ini_set('max_input_time', 300);
ini_set('max_execution_time', 300);
$filePath = "uploads/";
if (!file_exists($filePath)) {
if (!mkdir($filePath, 0777, true)) {
echo "Failed to create $filePath";
}
}
// $newfile = $newfile ."_". $_SESSION['counter'] .".mp4";
$target_path = 'uploads/';
$tmp_name = $_FILES['file']['tmp_name'];
$filename = $_FILES['file']['name'];
$newfile = substr(md5($_FILES['file']['name']), 0,10);
$target_file = $target_path.$newfile;
move_uploaded_file($tmp_name, $target_file.$_SESSION['counter'] );
B.U.T. the following .PHP code does not merge the chunks.
I do not really understand why it is not fopening for reading and writing...
If you have any ways of merging the chunks into one whole video file, please post your response likewise here.
// count number of uploaded chunks
$chunksUploaded = 0;
for ( $i = 1; $i <= $_SESSION['counter']; $i++ ) {
if ( file_exists( $target_file.$i ) ) {
$chunksUploaded++;
}
}
// if ($chunksUploaded === $num_chunks) {
if ($chunksUploaded === $_SESSION['counter']) {
// here you can reassemble chunks together
// for ($i = 1; $i <= $num_chunks; $i++) {
for ($i = 1; $i <= $_SESSION['counter']; $i++) {
// echo $i ."\n";
$file = fopen($target_file.$i, 'rb');
$buff = fread($file, 1048576);
fclose($file);
$final = fopen($target_file, 'ab');
$write = fwrite($final, $buff);
fclose($final);
unlink($target_file.$i);
}
}
Hope you enjoy and thank you for your contribution too.
I have find the corect javascript code :
(The PHP works fine)
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
var blob;
var start;
var end;
var part;
var SIZE;
var BYTES_PER_CHUNK;
var xhr;
var chunk;
function sendRequest() {
blob = document.getElementById('fileToUpload').files[0];
BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
SIZE = blob.size;
start = 0;
part = 0;
end = BYTES_PER_CHUNK;
chunk = blob.slice(start, end);
uploadFile(chunk,part);
start = end;
end = start + BYTES_PER_CHUNK;
part = part + 1;
};
//------------------------------------------------------------------------------------------------------------------------------------
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
};
//------------------------------------------------------------------------------------------------------------------------------------
function uploadFile(blobFile,part) {
var file = document.getElementById('fileToUpload').files[0];
var fd = new FormData();
fd.append("fileToUpload", blobFile);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
var php_file = "/upload.php"
xhr.open("POST", php_file +"?"+"file="+file.name+"&num=" + parseInt(part) );
xhr.onload = function(e) {
//alert("loaded!");
};
xhr.setRequestHeader('Cache-Control','no-cache');
xhr.send(fd);
return;
};
//------------------------------------------------------------------------------------------------------------------------------------
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + "%";
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
};
//------------------------------------------------------------------------------------------------------------------------------------
function uploadComplete(evt) {
// This event is raised when the server send back a response
//alert(evt.target.responseText);
if( start < SIZE ) {
chunk = blob.slice(start, end);
uploadFile(chunk,part);
start = end;
end = start + BYTES_PER_CHUNK;
part = part + 1;
}
};
//------------------------------------------------------------------------------------------------------------------------------------
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
};
//------------------------------------------------------------------------------------------------------------------------------------
function uploadCanceled(evt) {
xhr.abort();
xhr = null;
alert("The upload has been canceled by the user or the browser dropped the connection.");
};
//------------------------------------------------------------------------------------------------------------------------------------
Change this:
var blob;
var start;
var end;
var part;
var SIZE;
var BYTES_PER_CHUNK;
var xhr;
function sendRequest() {
blob = document.getElementById('fileToUpload').files[0];
// var file = document.getElementById('fileToUpload').files[0];
BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
SIZE = blob.size;
start = 0;
part = 0;
end = BYTES_PER_CHUNK;
while( start < SIZE ) {
var chunk = blob.slice(start, end);
//alert(chunk.size());
alert(start + ' - ' + end );
uploadFile(chunk,part);
//alert("here");
start = end;
end = start + BYTES_PER_CHUNK;
part++;
}
}
I think the problem is with xhr.onload or fileareader.onload which are the asynchronous methods so you can not use them in a for/while loop that are synchronous events. if you want to then, you have to use recursive method and make sure you are streaming the data correctly. here is my answer, I tested it locally and it works fine for any large file. I used fetch instead of XMLHTTPRequest. I also will wait for the server to response with the "file is received" text and if after numberOfTries (which I considered 5 times) I don't receive the "file is received" then I will break the recursion. I am wondering if anyone else has other approaches tested. Please let me know for any better solution.
window.BlobBuilder = window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder;
const btnUpload= document.getElementById('button1')
var blob = document.getElementById('fileToUpload').files[0];
const BYTES_PER_CHUNK = 1048576; // 1MB chunk sizes.
const SIZE = blob.size;
const CHUNK_COUNT= parseInt(SIZE/BYTES_PER_CHUNK)
var start = 0;
var i =0;
var part = 0;
const numberOfTries=5
function uploadFile(start,chunkCount,CHUNK_SIZE,theFile,NumberofTry){
// if you are done with recursive process then break
if (start > chunkCount+1){
fetch('/yourEndPoint',{
// you don't need to send the body just header is enough to let the endpoint know that can close the stream pipeline
//"body":ev.target.result,
"method":"POST",
"headers":{
"content-type":"application/octet-stream",
"finished-stream":true
}
})
return
}
var tmpBlob = theFile.slice(start*CHUNK_SIZE,(start+1)*CHUNK_SIZE)
var newReader = new FileReader()
newReader.onload = async ev=>{
let fileName= start+'__'+ Math.random()*1000+'__'+theFile.name
const serverResp= await fetch('/yourEndPoint',{
"body":ev.target.result,
"method":"POST",
"headers":{
"content-type":"application/octet-stream",
"file-name":fileName
}
})
let respText = await serverResp.text()
if (respText!=='file is received' && NumberofTry<5){
console.log('retry the upload again')
uploadFile(start,chunkCount,CHUNK_SIZE,theFile,NumberofTry+1)
}else if (respText!=='file is received' && NumberofTry===5){
console.log('upload can not be complete...')
return
}
uploadFile(start+1,chunkCount,CHUNK_SIZE,theFile,NumberofTry)
}
newReader.readAsArrayBuffer(tmpBlob)
}
btnUpload.addEventListener("click",()=>{
uploadFile(i,CHUNK_COUNT,BYTES_PER_CHUNK,blob,numberOfTries)
})
Related
I am trying to upload larger image file 100MB to php server.
It looks like a whole file uploaded (got status 200), but on server side there is wrong file size, lost few bytes, and it is not displayed as image in web browser.
How to fix?
Here is htmlp/javascript :
var file = document.getElementById("selectedfile").files[0];
var reader = new FileReader();
//reader.readAsBinaryString(file);
reader.readAsDataURL(file);
reader.onloadend = function(evt){
xhr = new XMLHttpRequest();
xhr.open("POST", "uprx.php?filename="+document.getElementById("selectedfile").files[0].name, true);
XMLHttpRequest.prototype.mySendAsBinary = function(text){
var data = new ArrayBuffer(text.length);
var ui8a = new Uint8Array(data, 0);
for (var i=0; i<text.length; i++) {
ui8a[i] = (text.charCodeAt(i)&0xff);
}
if (typeof window.Blob == "function") {
var blob = new Blob([data]);
}
else {
var bb = new (window.MozBlobBuilder || window.WebKitBlobBuilder || window.BlobBuilder)();
bb.append(data);
var blob = bb.getBlob();
}
this.send(blob);
}
var eventSource = xhr.upload || xhr;
eventSource.addEventListener("progress", function(e) {
var position = e.position || e.loaded;
var total = e.totalSize || e.total;
var percentage = Math.round((position/total)*100);
});
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
}
else {
// process error
}
}
};
xhr.mySendAsBinary(evt.target.result);
};
Here is php server :
$inputHandler = fopen("php://input", "r");
$fileHandler = fopen($_GET["filename"], "w");
while(true) {
$buffer = fgets($inputHandler, 4096);
if (strlen($buffer) == 0) {
fclose($inputHandler);
fclose($fileHandler);
return true;
}
$base64Image = trim($buffer);
$base64Image = str_replace('data:image/png;base64,', '', $base64Image);
$base64Image = str_replace('data:image/jpg;base64,', '', $base64Image);
$base64Image = str_replace('data:image/jpeg;base64,', '', $base64Image);
$base64Image = str_replace('data:image/gif;base64,', '', $base64Image);
//$base64Image = str_replace(' ', '+', $base64Image);
$imageData = base64_decode($base64Image);
fwrite($fileHandler, $imageData);
}
In my situation, I have images upload form with resize method but it failed. I have below code but does not know why where is the problem. Do you have any ideas? I am using PHP of codeingiter. Below is the error that shown. I have hosted the web site on goDaddy.
Request Entity Too Large The requested resource
/index.php/newPost/createNewPost/2/Raymond Chiu/ does not allow request data with GET requests, or the amount of data provided in the request exceeds the capacity limit. Additionally, a 500 Internal Server Error error was encountered while trying to use an ErrorDocument to handle the request.
//----font end php html code with javascript------------//
<input id="image1" name="image1" class="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-tw" onclick="setup(); return false;">Submit</button>
<script>
$("#image1").fileinput({
'showPreview' : true,
'allowedFileExtensions' : ['jpg', 'png','gif'],
'showUpload' : false,
'maxFileCount':1,
'maxFileSize': 800000,
});
$('#image1').on('fileclear', function(event) {
img1 = null;
});
$('#image1').on('fileloaded', function(event, file, previewId, index, reader) {
img1 = file;
$("#uploadImgError").html('');
});
function getResizeImage(pic, callback)
{
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
// Create an image
//-----------------------------Image-------------------------
var img = document.createElement("img");
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//document.getElementById('image').src = dataurl;
callback(dataurl);
}
reader.readAsDataURL(pic);
}
function isEmptyUploadFile(callback)
{
if(img1 == null && img2 == null && img3 == null && img4 == null && img5 == null)
callback(true);
else
callback(false);
}
function setForm(callback)
{
setImg1(function(data1)
{
if(data1 == true)
{
$('.progress-bar').css('width', 100+'%').attr('aria-valuenow', 100);
callback(true);
}
});
}
function setImg1(callback)
{
if(img1 != null)
{
getResizeImage(img1,function(tempPic)
{
document.getElementById('img1').value = tempPic;
getResizeThumbnailImage(img1,function(tempTPic)
{
document.getElementById('timg1').value = tempTPic;
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
});
});
}else{
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
}
}
function setup()
{
var myform = document.getElementById("newPost");
//console.log(myform.checkValidity());
if(!myform.checkValidity())
{
document.getElementById("validate").click();
return false;
}
isEmptyUploadFile(function(r)
{
var up1 = document.getElementById('image1').value;
var up2 = document.getElementById('image2').value;
var up3 = document.getElementById('image3').value;
var up4 = document.getElementById('image4').value;
var up5 = document.getElementById('image5').value;
if(r == true || (up1 == "" && up2 == "" && up3 == "" && up4 == "" && up5 == "") )
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
//var loc = document.getElementById('uploadImgError'); //Getting Y of target element
//window.scrollTo(0, loc);
location.href = "#uploadImgError"; //Go to the target element.
return false;
}
else if(r == false)
{
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
console.log(data);
if(data == true)
{
document.getElementById("newPost").submit();
}
return data;
});
}
});
}
</script>
// ------- controller ---------------------------//
$image1 = $this->input->post('img1');
$timage1 = $this->input->post('timg1');
$imgPath = '';
$timgPath = '';
$date=date_create();
if (isset($image1)) {
$currentTimeStamp = date_timestamp_get($date);
$imgPath = $upload_dir . '/['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($image1, false, $imgPath);
}
if (isset($timage1)) {
$currentTimeStamp = date_timestamp_get($date);
$timgPath = $upload_dir . '/[T]['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($timage1, true, $timgPath);
}
function uploadImg($input, $isThumbnail, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,'.base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
$maxFilesAllowed = 10;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
return true;
}
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
// this code said null value.
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
//-------------------end --------//
You have to configure your server to accept Large Files.
Also you're using GET.Use Post instead.
See So why should we use POST instead of GET
I may find out the reasons. After I am using native session in PHP from codeigniter session, I find that when I upload small images which will corrupt and cannot see picture. The image file that uploaded after resize in client side with above code.
Should it be reason??
In my situation, I have images upload form with resize method but it failed.
I have below code but does not know why where is the problem. Do you have any ideas? There is function in controller check_base64_image($base64) in which the code said there is null value. I am using PHP of codeingiter
//----font end php html code with javascript------------//
<input id="image1" name="image1" class="file" type="file" accept="image/*">
<button type="submit" class="btn btn-primary btn-tw" onclick="setup(); return false;">Submit</button>
<script>
$("#image1").fileinput({
'showPreview' : true,
'allowedFileExtensions' : ['jpg', 'png','gif'],
'showUpload' : false,
'maxFileCount':1,
'maxFileSize': 8000,
});
$('#image1').on('fileclear', function(event) {
img1 = null;
});
$('#image1').on('fileloaded', function(event, file, previewId, index, reader) {
img1 = file;
$("#uploadImgError").html('');
});
function getResizeImage(pic, callback)
{
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
// Create an image
//-----------------------------Image-------------------------
var img = document.createElement("img");
img.src = e.target.result;
var canvas = document.createElement("canvas");
//var canvas = $("<canvas>", {"id":"testing"})[0];
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var MAX_WIDTH = 800;
var MAX_HEIGHT = 800;
var width = img.width;
var height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
var dataurl = canvas.toDataURL("image/png");
//document.getElementById('image').src = dataurl;
callback(dataurl);
}
reader.readAsDataURL(pic);
}
function isEmptyUploadFile(callback)
{
if(img1 == null && img2 == null && img3 == null && img4 == null && img5 == null)
callback(true);
else
callback(false);
}
function setForm(callback)
{
setImg1(function(data1)
{
if(data1 == true)
{
$('.progress-bar').css('width', 100+'%').attr('aria-valuenow', 100);
callback(true);
}
});
}
function setImg1(callback)
{
if(img1 != null)
{
getResizeImage(img1,function(tempPic)
{
document.getElementById('img1').value = tempPic;
getResizeThumbnailImage(img1,function(tempTPic)
{
document.getElementById('timg1').value = tempTPic;
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
});
});
}else{
$('.progress-bar').css('width', 20+'%').attr('aria-valuenow', 20);
callback(true);
}
}
function setup()
{
var myform = document.getElementById("newPost");
//console.log(myform.checkValidity());
if(!myform.checkValidity())
{
document.getElementById("validate").click();
return false;
}
isEmptyUploadFile(function(r)
{
var up1 = document.getElementById('image1').value;
var up2 = document.getElementById('image2').value;
var up3 = document.getElementById('image3').value;
var up4 = document.getElementById('image4').value;
var up5 = document.getElementById('image5').value;
if(r == true || (up1 == "" && up2 == "" && up3 == "" && up4 == "" && up5 == "") )
{
$("#uploadImgError").html('<em><span style="color:red"> <i class="icon-cancel-1 fa"></i> Please Upload at least one image!</span></em>');
//var loc = document.getElementById('uploadImgError'); //Getting Y of target element
//window.scrollTo(0, loc);
location.href = "#uploadImgError"; //Go to the target element.
return false;
}
else if(r == false)
{
$('#pleaseWaitDialog').modal('show');
setForm(function(data)
{
console.log(data);
if(data == true)
{
document.getElementById("newPost").submit();
}
return data;
});
}
});
}
</script>
// ------- controller ---------------------------//
$image1 = $this->input->post('img1');
$timage1 = $this->input->post('timg1');
$imgPath = '';
$timgPath = '';
$date=date_create();
if (isset($image1)) {
$currentTimeStamp = date_timestamp_get($date);
$imgPath = $upload_dir . '/['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($image1, false, $imgPath);
}
if (isset($timage1)) {
$currentTimeStamp = date_timestamp_get($date);
$timgPath = $upload_dir . '/[T]['.$currentTimeStamp.']['.$userName.'].png';
$result = $this->uploadImg($timage1, true, $timgPath);
}
function uploadImg($input, $isThumbnail, $file)
{
if($input == null || $input == "")
{
return false;
}
$stringVal = $input;
$value = str_replace('data:image/png;base64,', '', $stringVal);
if ($this->check_base64_image($value) == false) {
return false;
}
$actualFile = base64_decode($value);
$img = imagecreatefromstring($actualFile);
$imgSize = getimagesize('data://application/octet-stream;base64,'.base64_encode($actualFile));
if ($img == false) {
return false;
}else
{
/*** maximum filesize allowed in bytes ***/
$max_file_length = 100000;
$maxFilesAllowed = 10;
log_message('debug', 'PRE UPLOADING!!!!!!!!');
if (isset($img)){
log_message('debug', 'UPLOADING!!!!!!!!');
// check the file is less than the maximum file size
if($imgSize['0'] > $max_file_length || $imgSize['1'] > $max_file_length)
{
log_message('debug', 'size!!!!!!!!'.print_r($imgSize));
$messages = "File size exceeds $max_file_size limit";
return false;
}else if (file_exists($file)) {
return false;
}else
{
return true;
}
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
// this code said null value.
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
//-------------------end --------//
I want to upload videos instead of images I have used this script for image uploads but now I want to upload videos and I have changed file types to video file types but it's not working and it is giving me this notification
Notice: Undefined index: file in C:\xampp\htdocs\mysql_login\upload.php on line 26
The file you attempted to upload is not allowed.
Here is my PHP Script:
<?php
if(!isset($_COOKIE['loggedin'])){
header("location:user_login.php");
}
session_start();
if(!isset($_SESSION['user'])){
header("location: user_login.php");
}
else {
?>
<?php
include("connection.php");
$current_page_URL =(isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"]==”on”) ? “https://” : “http://”;
$current_page_URL = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
$allowed_filetypes = array('.avi','.mp4','.wmv','.flv');
$max_filesize = 104857660;
$upload_path = 'uploads/';
$filename = $_FILES['file']['name'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
function bytesToSize1024($bytes, $precision = 2) {
$unit = array('B','KB','MB');
return #round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision).' '.$unit[$i];
}
$sFileName = $_FILES['file']['name'];
$sFileType = $_FILES['file']['type'];
$sFileSize = bytesToSize1024($_FILES['file']['size'], 1);
if (file_exists("uploads/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $_FILES["file"]["name"]);
echo "Stored in: ".$_SERVER["SERVER_NAME"]. "/uploads/" . $_FILES["file"]["name"];
}
$savefile = $_SERVER["SERVER_NAME"]. "/uploads/" . $_FILES["file"]["name"];
$insert_query = "insert into save_data (username, Name, Type, size, link) values ('".$_SESSION['user']."','$sFileName','$sFileType','$sFileSize','$savefile')";
if(mysql_query($insert_query)){
echo "<script>alert('Successfully added to DB')</script>";
}}
?>
Here is JS Script
// common variables
var iBytesUploaded = 0;
var iBytesTotal = 0;
var iPreviousBytesLoaded = 0;
var iMaxFilesize = 1048576; // 1MB
var oTimer = 0;
var sResultFileSize = '';
function secondsToTime(secs) { // we will use this function to convert seconds in normal time format
var hr = Math.floor(secs / 3600);
var min = Math.floor((secs - (hr * 3600))/60);
var sec = Math.floor(secs - (hr * 3600) - (min * 60));
if (hr < 10) {hr = "0" + hr; }
if (min < 10) {min = "0" + min;}
if (sec < 10) {sec = "0" + sec;}
if (hr) {hr = "00";}
return hr + ':' + min + ':' + sec;
};
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
function fileSelected() {
// hide different warnings
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
// get selected file element
var oFile = document.getElementById('vid_file').files[0];
// filter for image files
var rFilter = /^(video\/mp4|video\/flv|video\/wmv|video\/avi)$/i;
if (! rFilter.test(oFile.type)) {
document.getElementById('error').style.display = 'block';
return;
}
// little test for filesize
if (oFile.size > iMaxFilesize) {
document.getElementById('warnsize').style.display = 'block';
return;
}
// get preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function(e){
// e.target.result contains the DataURL which we will use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // binding onload event
// we are going to display some custom image information here
sResultFileSize = bytesToSize(oFile.size);
document.getElementById('fileinfo').style.display = 'block';
document.getElementById('filename').innerHTML = 'Name: ' + oFile.name;
document.getElementById('filesize').innerHTML = 'Size: ' + sResultFileSize;
document.getElementById('filetype').innerHTML = 'Type: ' + oFile.type;
document.getElementById('filedim').innerHTML = 'Dimension: ' + oImage.naturalWidth + ' x ' + oImage.naturalHeight;
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
function startUploading() {
// cleanup all temp states
iPreviousBytesLoaded = 0;
document.getElementById('upload_response').style.display = 'none';
document.getElementById('error').style.display = 'none';
document.getElementById('error2').style.display = 'none';
document.getElementById('abort').style.display = 'none';
document.getElementById('warnsize').style.display = 'none';
document.getElementById('progress_percent').innerHTML = '';
var oProgress = document.getElementById('progress');
oProgress.style.display = 'block';
oProgress.style.width = '0px';
// get form data for POSTing
//var vFD = document.getElementById('upload_form').getFormData(); // for FF3
var vFD = new FormData(document.getElementById('upload_form'));
// create XMLHttpRequest object, adding few event listeners, and POSTing our data
var oXHR = new XMLHttpRequest();
oXHR.upload.addEventListener('progress', uploadProgress, false);
oXHR.addEventListener('load', uploadFinish, false);
oXHR.addEventListener('error', uploadError, false);
oXHR.addEventListener('abort', uploadAbort, false);
oXHR.open('POST', 'upload.php');
oXHR.send(vFD);
// set inner timer
oTimer = setInterval(doInnerUpdates, 300);
}
function doInnerUpdates() { // we will use this function to display upload speed
var iCB = iBytesUploaded;
var iDiff = iCB - iPreviousBytesLoaded;
// if nothing new loaded - exit
if (iDiff == 0)
return;
iPreviousBytesLoaded = iCB;
iDiff = iDiff * 2;
var iBytesRem = iBytesTotal - iPreviousBytesLoaded;
var secondsRemaining = iBytesRem / iDiff;
// update speed info
var iSpeed = iDiff.toString() + 'B/s';
if (iDiff > 1024 * 1024) {
iSpeed = (Math.round(iDiff * 100/(1024*1024))/100).toString() + 'MB/s';
} else if (iDiff > 1024) {
iSpeed = (Math.round(iDiff * 100/1024)/100).toString() + 'KB/s';
}
document.getElementById('speed').innerHTML = iSpeed;
document.getElementById('remaining').innerHTML = '| ' + secondsToTime(secondsRemaining);
}
function uploadProgress(e) { // upload process in progress
if (e.lengthComputable) {
iBytesUploaded = e.loaded;
iBytesTotal = e.total;
var iPercentComplete = Math.round(e.loaded * 100 / e.total);
var iBytesTransfered = bytesToSize(iBytesUploaded);
document.getElementById('progress_percent').innerHTML = iPercentComplete.toString() + '%';
document.getElementById('progress').style.width = (iPercentComplete * 4).toString() + 'px';
document.getElementById('b_transfered').innerHTML = iBytesTransfered;
if (iPercentComplete == 100) {
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = '<h1>Please wait...processing</h1>';
oUploadResponse.style.display = 'block';
}
} else {
document.getElementById('progress').innerHTML = 'unable to compute';
}
}
function uploadFinish(e) { // upload successfully finished
var oUploadResponse = document.getElementById('upload_response');
oUploadResponse.innerHTML = e.target.responseText;
oUploadResponse.style.display = 'block';
document.getElementById('progress_percent').innerHTML = '100%';
document.getElementById('progress').style.width = '400px';
document.getElementById('filesize').innerHTML = sResultFileSize;
document.getElementById('remaining').innerHTML = '| 00:00:00';
clearInterval(oTimer);
}
function uploadError(e) { // upload error
document.getElementById('error2').style.display = 'block';
clearInterval(oTimer);
}
function uploadAbort(e) { // upload abort
document.getElementById('abort').style.display = 'block';
clearInterval(oTimer);
}
HTML File
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="utf-8" />
<title>Pure HTML5 file upload | Script Tutorials</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<script src="js/script.js"></script>
</head>
<body>
<div class="container">
<div class="contr"><h2>You can select the file (image) and click Upload button</h2></div>
<div class="upload_form_cont">
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php">
<div>
<div><label for="file">Please select image file</label></div>
<div><input type="file" name="file" id="file" onchange="fileSelected();" /></div>
</div>
<div>
<input type="button" value="Upload" onclick="startUploading()" />
</div>
<div id="fileinfo">
<div id="filename"></div>
<div id="filesize"></div>
<div id="filetype"></div>
<div id="filedim"></div>
</div>
<div id="error">You should select valid image files only!</div>
<div id="error2">An error occurred while uploading the file</div>
<div id="abort">The upload has been canceled by the user or the browser dropped the connection</div>
<div id="warnsize">Your file is very big. We can't accept it. Please select more small file</div>
<div id="progress_info">
<div id="progress"></div>
<div id="progress_percent"> </div>
<div class="clear_both"></div>
<div>
<div id="speed"> </div>
<div id="remaining"> </div>
<div id="b_transfered"> </div>
<div class="clear_both"></div>
</div>
<div id="upload_response"></div>
</div>
<div>
</div>
</form>
<img id="preview" />
</div>
</div>
</body>
</html>
Check the extension of the file being uploaded.
So,simply do
echo $ext;
See if it matches the values in the array. Chances are it doesn't.
Hope this helps.
Been working on this annoying son of a gun for 3 days. Hoping someone will be able to offer some assistance. Basically I'm using http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/ to allow multiple file uploads along side with a regular file upload input. The first part of this code is the copying of the original image that was uploaded. That works fine for both. The second part is for thumbnails and it won't work when using the drag-drop script, however it works perfectly using the standard upload. I'm assuming my problem isn't with this code, but I'm including it just to show you. I'll also include almost all the other code in case you find it pertinent and helpful in diagnosing.
// copying original image to new location with new name
$prev = file_get_contents($pic['tmp_name']);
$new = fopen($file, "w");
fwrite($new, $prev);
fclose($new);
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
$image = imagecreatefromjpeg($pic['tmp_name']);
break;
case 'image/png':
$image = imagecreatefrompng($pic['tmp_name']);
imagealphablending($image, true); // setting alpha blending on
imagesavealpha($image, true);
break;
case 'image/gif':
$image = imagecreatefromgif($pic['tmp_name']);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
// Target dimensions
$max_width = 150;
$max_height = 150;
// Get current dimensions
$old_width = imagesx($image);
$old_height = imagesy($image);
// Calculate the scaling we need to do to fit the image inside our frame
$scale = min($max_width/$old_width, $max_height/$old_height);
// Get the new dimensions
$new_width = ceil($scale*$old_width);
$new_height = ceil($scale*$old_height);
// Create new empty image
$new = imagecreatetruecolor($new_width, $new_height);
// Resize old image into new
imagecopyresampled($new, $image, 0, 0, 0, 0, $new_width, $new_height, $old_width, $old_height);
// Catch the imagedata
ob_start();
//create image for thumbnail
switch(strtolower($pic['type']))
{
case 'image/jpeg':
imagejpeg($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 90);
break;
case 'image/png';
imagepng($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
case 'image/gif':
imagegif($new, $_SERVER['DOCUMENT_ROOT']."/".$thumbnail, 9);
break;
default:
exit('Unsupported type: '.$pic['type']);
}
chmod($_SERVER['DOCUMENT_ROOT']."/".$thumbnail,0755);
$data = ob_get_clean();
// Destroy resources
imagedestroy($image);
imagedestroy($new);
The HTML
<h1>Upload Image(s)</h1>
<form action='ajax/post_file.php' method='post' enctype="multipart/form-data">
<input type='file' name='file'><input type='hidden' name='drag_drop' value='yes'><input type='submit' value='go'>
</form>
<!-- Our CSS stylesheet file -->
<link rel="stylesheet" href="ajax/drag_drop_uploads/css/styles.css" />
<div id="dropbox" style='height: 400px; overflow: auto;'>
<span class="message">Drop images here to upload. <br /><i>(they will be automatically uploaded to your account)</i></span>
</div>
The JQuery plugin that handles the drag-drop upload
(function(jQuery){
jQuery.event.props.push("dataTransfer");
var opts = {},
default_opts = {
url: '',
refresh: 1000,
paramname: 'userfile',
maxfiles: 25,
maxfilesize: 5, // MBs
data: {},
drop: empty,
dragEnter: empty,
dragOver: empty,
dragLeave: empty,
docEnter: empty,
docOver: empty,
docLeave: empty,
beforeEach: empty,
afterAll: empty,
rename: empty,
error: function(err, file, i){alert(err);},
uploadStarted: empty,
uploadFinished: empty,
progressUpdated: empty,
speedUpdated: empty
},
errors = ["BrowserNotSupported", "TooManyFiles", "FileTooLarge"],
doc_leave_timer,
stop_loop = false,
files_count = 0,
files;
jQuery.fn.filedrop = function(options) {
opts = jQuery.extend( {}, default_opts, options );
this.bind('drop', drop).bind('dragenter', dragEnter).bind('dragover', dragOver).bind('dragleave', dragLeave);
jQuery(document).bind('drop', docDrop).bind('dragenter', docEnter).bind('dragover', docOver).bind('dragleave', docLeave);
};
function drop(e) {
opts.drop(e);
files = e.dataTransfer.files;
if (files === null || files === undefined) {
opts.error(errors[0]);
return false;
}
files_count = files.length;
upload();
e.preventDefault();
return false;
}
function getBuilder(filename, filedata, boundary) {
var dashdash = '--',
crlf = '\r\n',
builder = '';
jQuery.each(opts.data, function(i, val) {
if (typeof val === 'function') val = val();
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+i+'"';
builder += crlf;
builder += crlf;
builder += val;
builder += crlf;
});
builder += dashdash;
builder += boundary;
builder += crlf;
builder += 'Content-Disposition: form-data; name="'+opts.paramname+'"';
builder += '; filename="' + filename + '"';
builder += crlf;
builder += 'Content-Type: application/octet-stream';
builder += crlf;
builder += crlf;
builder += filedata;
builder += crlf;
builder += dashdash;
builder += boundary;
builder += dashdash;
builder += crlf;
return builder;
}
function progress(e) {
if (e.lengthComputable) {
var percentage = Math.round((e.loaded * 100) / e.total);
if (this.currentProgress != percentage) {
this.currentProgress = percentage;
opts.progressUpdated(this.index, this.file, this.currentProgress);
var elapsed = new Date().getTime();
var diffTime = elapsed - this.currentStart;
if (diffTime >= opts.refresh) {
var diffData = e.loaded - this.startData;
var speed = diffData / diffTime; // KB per second
opts.speedUpdated(this.index, this.file, speed);
this.startData = e.loaded;
this.currentStart = elapsed;
}
}
}
}
function upload() {
stop_loop = false;
if (!files) {
opts.error(errors[0]);
return false;
}
var filesDone = 0,
filesRejected = 0;
if (files_count > opts.maxfiles) {
opts.error(errors[1]);
return false;
}
for (var i=0; i<files_count; i++) {
if (stop_loop) return false;
try {
if (beforeEach(files[i]) != false) {
if (i === files_count) return;
var reader = new FileReader(),
max_file_size = 1048576 * opts.maxfilesize;
reader.index = i;
if (files[i].size > max_file_size) {
opts.error(errors[2], files[i], i);
filesRejected++;
continue;
}
reader.onloadend = send;
reader.readAsBinaryString(files[i]);
} else {
filesRejected++;
}
} catch(err) {
opts.error(errors[0]);
return false;
}
}
function send(e) {
// Sometimes the index is not attached to the
// event object. Find it by size. Hack for sure.
if (e.target.index == undefined) {
e.target.index = getIndexBySize(e.total);
}
var xhr = new XMLHttpRequest(),
upload = xhr.upload,
file = files[e.target.index],
index = e.target.index,
start_time = new Date().getTime(),
boundary = '------multipartformboundary' + (new Date).getTime(),
builder;
newName = rename(file.name);
if (typeof newName === "string") {
builder = getBuilder(newName, e.target.result, boundary);
} else {
builder = getBuilder(file.name, e.target.result, boundary);
}
upload.index = index;
upload.file = file;
upload.downloadStartTime = start_time;
upload.currentStart = start_time;
upload.currentProgress = 0;
upload.startData = 0;
upload.addEventListener("progress", progress, false);
xhr.open("POST", opts.url, true);
xhr.setRequestHeader('content-type', 'multipart/form-data; boundary='
+ boundary);
xhr.sendAsBinary(builder);
opts.uploadStarted(index, file, files_count);
xhr.onload = function() {
if (xhr.responseText) {
var now = new Date().getTime(),
timeDiff = now - start_time,
result = opts.uploadFinished(index, file, jQuery.parseJSON(xhr.responseText), timeDiff);
filesDone++;
if (filesDone == files_count - filesRejected) {
afterAll();
}
if (result === false) stop_loop = true;
}
};
}
}
function getIndexBySize(size) {
for (var i=0; i < files_count; i++) {
if (files[i].size == size) {
return i;
}
}
return undefined;
}
function rename(name) {
return opts.rename(name);
}
function beforeEach(file) {
return opts.beforeEach(file);
}
function afterAll() {
return opts.afterAll();
}
function dragEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.dragEnter(e);
}
function dragOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
opts.dragOver(e);
}
function dragLeave(e) {
clearTimeout(doc_leave_timer);
opts.dragLeave(e);
e.stopPropagation();
}
function docDrop(e) {
e.preventDefault();
opts.docLeave(e);
return false;
}
function docEnter(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docEnter(e);
return false;
}
function docOver(e) {
clearTimeout(doc_leave_timer);
e.preventDefault();
opts.docOver(e);
return false;
}
function docLeave(e) {
doc_leave_timer = setTimeout(function(){
opts.docLeave(e);
}, 200);
}
function empty(){}
try {
if (XMLHttpRequest.prototype.sendAsBinary) return;
XMLHttpRequest.prototype.sendAsBinary = function(datastr) {
function byteValue(x) {
return x.charCodeAt(0) & 0xff;
}
var ords = Array.prototype.map.call(datastr, byteValue);
var ui8a = new Uint8Array(ords);
this.send(ui8a.buffer);
}
} catch(e) {}
})(jQuery);
The JQuery that is called to and from the plugin
jQuery(function(){
var dropbox = jQuery('#dropbox'),
message = jQuery('.message', dropbox);
dropbox.filedrop({
// The name of the jQuery_FILES entry:
paramname:'file',
maxfiles: 25,
maxfilesize: 5,
url: 'ajax/post_file.php',
uploadFinished:function(i,file,response){
jQuery.data(file).addClass('done');
// response is the JSON object that post_file.php returns
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 5 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 2mb (configurable).');
break;
default:
break;
}
},
// Called before each upload is started
beforeEach: function(file){
if(!file.type.match(/^image\//)){
alert('Only images are allowed!');
// Returning false will cause the
// file to be rejected
return false;
}
},
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
jQuery.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = jQuery(template),
image = jQuery('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's jQuery.data():
jQuery.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
The sample PHP they gave me
$demo_mode = false;
$upload_dir = 'ajax/uploads/';
$allowed_ext = array('jpg','jpeg','png','gif');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
if(!in_array(get_extension($pic['name']),$allowed_ext)){
exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'],
$pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
As discussed in the OPs comments;
It seems the file upload example isn't correctly populating the filetype resulting in hitting the switch's default block (an exit)
Incidentally, you may want to swap this to throwing an exception so you'll see something useful in the logs in future