How to make progress bar on Ajax Upload - javascript

Hi I am using Ajax Upload JS 3.5 is there a way to make a progress upon uploading of image / File ?. All I see in my net is by using the <input type="file"> button and my project is not a bootstrap.
Here is my currently code
jQuery(document).ready(function () {
var extension = "";
var btnUploadDrvr = $("#btnFitaDocBrowse");
var hidFilenameDrvr = $("#imgFitaDoc");
var hidDoccFrame = $("#frmFitaDoc");
InitAjaxUpload(btnUploadDrvr, hidFilenameDrvr, hidDoccFrame );
function InitAjaxUpload(btnUpload, imgHolder, hidDoccFrame) {
new AjaxUpload(btnUpload, {
action: '../UploadDownload/UploadLocalPic',
data: '',
name: 'uploadfile',
onSubmit: function (file, ext) {
extension = ext[0];
if (!(ext && /^(jpg|png|jpeg|gif|pdf|PDF)$/.test(ext))) {
alert("File format is not supported.");
return false;
}
},
onComplete: function (file, response) {
//Add uploaded file to list
if (response !== "failed") {
$("#frmFitaDoc").attr('src', 'data:application/pdf;base64,' + response);
}
}
});
}
});
And I saw this can this be possible to embed in my code?.

Related

Ajax Upload popup window not showing

I am new to Ajax Upload and use http://valums.com/ajax-upload js file to cater for my upload file function. As i try to click the button for ajax upload...the pop up window to select file is not showing so i was unable to select file. Below is my button and code to trigger ajax upload.
<button class="pbutton btn-glossy-black" id="browseFile">Browse</button>
var upload = new AjaxUpload('browseFile', {
action: jq_main_url + 'candidates/upload_attachment/' + main_folder_name,
name: 'upload_file',
data:{ 'countchecklist': 0},
onComplete: function(file, response) {
try {
var json = JSON.parse(response);
if(json.status == 'OK'){
alert('Complete');
} else {
core.jq_message(messageLevel, json.message);
}
} catch(e){
core.jq_message(messageLevel, e.message);
}
}
});

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

Ajax posting on localhost but not on VPS host

I've been facing this issue for many days i've searched the whole internet fixed my php.ini even the ngnix.confg file
Please tell me if anything is wrong with the code
i've edited the Cropper Plugin not to download but replace the current image.
so what i did i used the ajax post to do it.
PS: Ajax is sending huge data in post since it's a canvas and this whole process is working fine on localhost but not working on server. The whole site is on laravel but this code is on native php.
I've also figured out that if image is small then it's working fine and if image is large then it's not working on server.
AJAX code in main.js file
$('.docs-buttons').on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
console.log(e.message);
}
}
}
if (data.method === 'rotate') {
$image.cropper('clear');
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.method === 'rotate') {
$image.cropper('crop');
}
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
var temp = $(' #image').attr('src');
jQuery.ajax({
url: '../../cropper/demo/save.php',
type: 'POST',
data: {
data: result.toDataURL('image/jpeg'),
name: temp,
},
complete: function(data, status)
{
console.log(data.responseText);
if(status=='success')
{
$('#image').cropper("replace", temp);
}
else
{
alert('Error has been occurred');
}
}
});
}
break;
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
console.log(e.message);
}
}
}
});
save.php (To store the image on server)
<?php
$based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1);
$fileName='';
$fileName = substr($_POST['name'], 34);
$image = imagecreatefromstring(base64_decode($based64Image));
if($image != false)
{
if(!imagejpeg($image,"..\..\images\image\\".$fileName))
{
// fail;
}
}
else
{
// fail;
}
?>
Please Help Thanks
Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
For more details and understanding please read
https://gist.github.com/magnetikonline/11312172#determine-fastcgi-response-sizes
These results may not be accurate, so reading to ensure your proper configuration is advised

Is there a way not to let a blob (createObjectURL) show the image which is a GIF file but has a .jpeg extension?

Using blueimp, I'm making a file upload module and I will show an image thumbnail before people upload the image.
My code contains the following:
$('.fileupload').fileupload({
dataType: 'json',
autoUpload: false,
acceptFileTypes: /(\.|\/)(jpe?g|png)$/i,
maxNumberOfFiles: 1,
maxFileSize: 3000000,//3MB
loadImageMaxFileSize: 3000000,//3MB
}).on('fileuploadsubmit', function (e, data) {
}).on('fileuploadadd', function (e, data) {
data.context = $('<div/>').appendTo('.files');
$.each(data.files, function (index, file) {
// ファイル情報を表示する
var node = $('<p/>')
.append($('<span/>').text(file.name));
// プレビューを表示する
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
node.append('<img class= "uploaded-image" src="'
+ URL.createObjectURL(data.files[0]) + '"/><br>');
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}
node.appendTo(data.context);
});
}) // .on(... code following
It works well, but if people change a GIF file extension to ".jpeg" and upload it, the blob will also work well to show the GIF and, I think it's not safe. Is there a way not let blob to show the thumbnail In this case?
When submit the file, I'm checking the file in the server side if the file is really an image file (although it has a valid extension).
(this link helped me)
The code below worked well:
if (!index) {
node.append('<br>');
if((/\.(jpe?g|png)$/i).test(data.files[0].name))
{
if (window.FileReader && window.Blob)
{
var blob = data.files[0]; // See step 1 above
var fileReader = new FileReader();
fileReader.onloadend = function(e) {
var arr = (new Uint8Array(e.target.result)).subarray(0, 4);
var header = "";
for(var i = 0; i < arr.length; i++) {
header += arr[i].toString(16);
}
if((header == "89504e47") || (header.substr(0,6) == "ffd8ff"))
{
$("button.upload").before('<img class= "uploaded-image" src="' + URL.createObjectURL(data.files[0]) + '"/><br>');
$(".file_upload").attr("style", "height: 600px; overflow-y: auto");
}
else
{
$("button.upload").prop('disabled', true);
var error = $('<span class="text-danger"/>').text(msg[4]);
$('.files').append('<br>').append(error);
}
};
fileReader.readAsArrayBuffer(blob);
}
}
node.append(uploadButton.clone(true).data(data))
.append(cancelButton);
}

In phonegap File Reader is not reading the file by using the path getting by FILE_URI

I am new to to the developing phonegap application. I need to choose the picture from the photolibrary after that need to store the path of the selected picture in localStorage, still this i did using destinationType as FILE_URI then i need to call another function which helps to converting the selected picture into base64 string by using File Reader's property readAsDataURL and upload that string to the server. The first part is working fine but that second part is not working please help me to solve this problem.
My HTML page is,
<button class="button" onclick="uploadImage();">From Photo Library</button>
<img style="display:none;width:60px;height:60px;" id="largeImage" src="" />
<button class="button" onclick="syncData();">Sync Data</button>
My Script.js is,
var pictureSource; // picture source
var destinationType;
document.addEventListener("deviceready",onDeviceReady,false);
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
var pictureSource = navigator.camera.PictureSourceType;
var destinationType = navigator.camera.DestinationType;
function uploadImage(){
alert('called upload pic');
//Using library
navigator.camera.getPicture(uploadPhoto, onFailcapturePhoto, { quality: 50,
destinationType: destinationType.FILE_URI, sourceType: pictureSource.PHOTOLIBRARY});
}
function onFailcapturePhoto(message) {
alert("Message = " + message);
}
function uploadPhoto(imageURI) {
if(!localStorage.imageArray) {
var imageArray = [];
imageArray.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imageArray));
alert(JSON.stringify(imageArray));
} else {
var imagefile = JSON.parse(localStorage.imageArray);
imagefile.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imagefile));
alert(JSON.stringify(imagefile));
}
var largeImage = document.getElementById('largeImage');
largeImage.style.display = 'block';
largeImage.src = imageURI; // here i can display the image
}
function syncData() {
var reader = new FileReader();
var selectedImageArray = [];
function readFile(index) {
alert('in read file'); // here i am getting alert
if( index >= JSON.parse(localStorage.imageArray).length ) return;
var file = JSON.parse(localStorage.imageArray)[index];
alert('file=='+file); // here i am getting path
reader.onloadend = function(e) {
// get file content
alert('in loadend');
selectedImageArray[index] = e.target.result;
alert('image data==:>'+selectedImageArray[index])
readFile(index+1);
}
if(file) {
alert('going to read'); // i got alert here, after this line i don't get anything
reader.readAsDataURL(file);
alert('reading finished');
} else {
alert('Your Browser does not support File Reader..');
}
}
readFile(0);
alert('before clear'+JSON.stringify(localStorage.imageArray));
localStorage.clear();
alert('after clear'+JSON.stringify(localStorage.imageArray));
}
Thanks & Regards,
Murali Selvaraj
By Following code i got answer for my question..
big thanks to this author..
my updated code is:
function uploadPhoto(imageURI) {
if (imageURI.substring(0,21)=="content://com.android") {
photo_split=imageURI.split("%3A");
imageURI="content://media/external/images/media/"+photo_split[1];
alert('new uri'+imageURI);
}
if(!localStorage.imageArray) {
var imageArray = [];
imageArray.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imageArray));
alert(JSON.stringify(imageArray));
} else {
var imagefile = JSON.parse(localStorage.imageArray);
imagefile.push(imageURI);
localStorage.setItem('imageArray',JSON.stringify(imagefile));
alert(JSON.stringify(imagefile));
}
}
function syncData() {
var selectedImageArray = new Array();
function readFile(index) {
if( index >= JSON.parse(localStorage.imageArray).length ) {
if(selectedImageArray.length == 0) return;
$.ajax({
url : 'Here place your api', //your server url where u have to upload
type : 'POST',
dataType : 'JSON',
contentType : 'application/json',
data : JSON.stringify(selectedImageArray)
})
.done(function(res) {
alert('success='+res);
localStorage.clear();
})
.error(function(err) {
alert('error='+err);
});
} else {
var filePath = JSON.parse(localStorage.imageArray)[index];
window.resolveLocalFileSystemURI(filePath, function(entry) {
var reader = new FileReader();
reader.onloadend = function(evt) {
selectedImageArray.push(evt.target.result);
readFile(index+1);
}
reader.onerror = function(evt) {
alert('read error');
alert(JSON.stringify(evt));
}
entry.file(function(f) {
reader.readAsDataURL(f)
}, function(err) {
alert('error='+err);
});
});
}
}
readFile(0);
}

Categories