jQuery + PHP Multi-File Drag-Drop Upload Can't Create Thumbnails - WEIRD - php

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

Related

Uploading larger image file from javascript XMLHttpRequest blob to php (it saved wrong size)

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);
}

imagecopyresampled() my image turns black after resizing it- CakePhp3

This when I send ajax request to my controller to crop and resize it, instead it resize it but my image turns black. I even tried adding header so that my browser can understands that it is a valid image file format. Where I am missing?
**My ajax call to controller**
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#change-pic').on('click', function(e){
jQuery('#changePic').show();
jQuery('#change-pic').hide();
});
jQuery('#photoimg').on('change', function()
{
jQuery("#preview-avatar-profile").html('');
jQuery("#preview-avatar-profile").html('Uploading....');
jQuery("#cropimage").ajaxForm(
{
target: '#preview-avatar-profile',
success: function() {
jQuery('img#photo').imgAreaSelect({
aspectRatio: '1:1',
onSelectEnd: getSizes,
});
jQuery('#image_name').val(jQuery('#photo').attr('file-name'));
}
}).submit();
});
jQuery('#btn-crop').on('click', function(e){
e.preventDefault();
params = {
//targetUrl: 'profile.php?action=save',
targetUrl: 'http://172.16.0.60/cakephp/users/croppedimage',
//action: 'save',
x_axis: jQuery('#hdn-x1-axis').val(),
y_axis : jQuery('#hdn-y1-axis').val(),
x2_axis: jQuery('#hdn-x2-axis').val(),
y2_axis : jQuery('#hdn-y2-axis').val(),
thumb_width : jQuery('#hdn-thumb-width').val(),
thumb_height:jQuery('#hdn-thumb-height').val()
};
saveCropImage(params);
});
function getSizes(img, obj)
{
var x_axis = obj.x1;
var x2_axis = obj.x2;
var y_axis = obj.y1;
var y2_axis = obj.y2;
var thumb_width = obj.width;
var thumb_height = obj.height;
if(thumb_width > 0)
{
jQuery('#hdn-x1-axis').val(x_axis);
jQuery('#hdn-y1-axis').val(y_axis);
jQuery('#hdn-x2-axis').val(x2_axis);
jQuery('#hdn-y2-axis').val(y2_axis);
jQuery('#hdn-thumb-width').val(thumb_width);
jQuery('#hdn-thumb-height').val(thumb_height);
}
else
alert("Please select portion..!");
}
function saveCropImage(params) {
jQuery.ajax({
url: params['targetUrl'],
cache: false,
dataType: "html",
data: {
action: params['action'],
id: jQuery('#hdn-profile-id').val(),
t: 'ajax',
w1:params['thumb_width'],
x1:params['x_axis'],
h1:params['thumb_height'],
y1:params['y_axis'],
x2:params['x2_axis'],
y2:params['y2_axis'],
image_name :jQuery('#image_name').val()
},
type: 'Post',
// async:false,
success: function (response) {
jQuery('#changePic').hide();
jQuery('#change-pic').show();
jQuery(".imgareaselect-border1,.imgareaselect-border2,.imgareaselect-border3,.imgareaselect-border4,.imgareaselect-border2,.imgareaselect-outer").css('display', 'none');
jQuery("#avatar-edit-img").attr('src', response);
jQuery("#preview-avatar-profile").html('');
jQuery("#photoimg").val('');
},
error: function (xhr, ajaxOptions, thrownError) {
alert('status Code:' + xhr.status + 'Error Message :' + thrownError);
}
});
}
});
</script>
This is one first when I upload the image and preview it.
public function wall()
{
$post = isset($_POST) ? $_POST: array();
$max_width = "500";
$userId = isset($post['hdn-profile-id']) ? intval($post['hdn-profile-id']) : 0;
// $path = 'http://172.16.0.60/cakephp/webroot/img/tmp';
$path = WWW_ROOT.'img/tmp/' ;
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = 'avatar' .'_'.$userId .'.'.$ext;
$filePath = $path .'/'.$actual_image_name;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $filePath))
{
// /$this->setPassword($this->request->data['password']);
$width = $this->getWidth($filePath);
$height = $this->getHeight($filePath);
//Scale the image if it is greater than the width set above
if ($width > $max_width)
{
$scale = $max_width/$width;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
else
{
$scale = 1;
$uploaded = $this->resizeImage($filePath,$width,$height,$scale);
}
/*
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".'file://'.$filePath.'?'.time()."' class='preview'/>";
*/
$mypath = '/cakephp/img/tmp/'.$actual_image_name;
echo "<img id='photo' file-name='".$actual_image_name."' class='' src='".$mypath."' class='preview'/>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
My Controller code where I use the function imagecopyresampled() but idk where I am going wrong.?
Any solution
public function croppedimage()
{
header('Content-Type: image/png');
$post = isset($_POST) ? $_POST: array();
$userId = isset($post['id']) ? intval($post['id']) : 0;
//$path ='\images\uploads\tmp';
$path = WWW_ROOT.'img/tmp/uploads/' ;
$t_width = 300; // Maximum thumbnail width
$t_height = 300; // Maximum thumbnail height
if(isset($_POST['t']) and $_POST['t'] == "ajax")
{
extract($_POST);
//$img = get_user_meta($userId, 'user_avatar', true);
//$filePath = $path .'/'.$actual_image_name;
$imagePath = $path.$_POST['image_name'];
$ratio = ($t_width/$w1);
$nw = ceil($w1 * $ratio);
$nh = ceil($h1 * $ratio);
$nimg = imagecreatetruecolor($nw,$nh);
$im_src = imagecreatefromjpeg($imagePath);
imagecopyresampled($nimg,$im_src,0,0,$x1,$y1,$nw,$nh,$w1,$h1);
imagejpeg($nimg,$imagePath,90);
}
echo $imagePath.'?'.time();;
exit(0);
die();
}

Cannot upload images -- Request Entity Too Large The requested resource

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??

Cannot upload images php codeigniter

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 --------//

Javascript large file uploader

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)
})

Categories