upload multiple file via jquery - javascript

This is my jquery code to upload multiple file. Input file generated dynamically so i am calling this FileUploader function where these input file generated. But I have to click twice to upload file. Any ideas are appreciated.
FileUploader: function($dis) {
var fileName = '';
var $htm = $($dis.parents('div.sfFormInput').find('div.cssClassUploadFiles'));
var $ht = $($dis.parent('div.uploader'));
var extension = new RegExp($ht.attr('extension'), "i");
var upload = new AjaxUpload($('#' + $dis.attr('id') + ''), {
action: Path + "UploadHandler.ashx",
name: "myfile[]",
multiple: true,
data: {},
autoSubmit: true,
responseType: "json",
onChange: function(file, ext) {
},
onSubmit: function(file, ext) {
if ($ht.attr('almul') == "false" && $('div.cssClassUploadFiles').children('div').length > 0) {
csscody.alert('<h1>Alert Message</h1><p>You can upload only one file at a time!</p>');
return false;
}
if (ext != "exe" && extension != '') {enter code here
if (ext && extension.test(ext)) {
this.setData({
'MaxFileSize': $ht.attr('filesize')
});
} else {
csscody.alert('<h1>Alert Message</h1><p>Not a valid file!</p>');
return false;
}
}
},
onComplete: function(file, response) {
var html = '';
var filePath = Path + "/UploadedFiles + file;
if (file.split('.')[1] == "jpg" || file.split('.')[1] == "JPEG" || file.split('.')[1] == "gif" || file.split('.')[1] == "bmp" || file.split('.')[1] == "png")
html = '<div title="' + Path + "UploadedFiles + file + '" ><img height="10%" width="10%" src="' + filePath + '"/><a class="sfDeleteFile"><img src="../Modules/FormBuilder/images/closelabel.png" /></a></div>';
else
html = '<div title="' + Path + "UploadedFiles + file + '" >' + file + ' <a class="sfDeleteFile"><img src="../Modules/FormBuilder/images/closelabel.png" /></a></div>';
$htm.append(html);
}
});
}
Code works but only issue is I have to click twice to upload file.

The problem is not with the fileuploading part, rather looks like in the initialization part. If your file upload control is dynamically created make sure you initialize the uploader after binding that in your markup.

Related

Multiple File Upload To Display File Names Only

I have a need to get the JSFIDDLE DEMO to keep the ability to upload multiple files, but instead displaying the preview, I need to display the multiple file names only.
Here's the JSFIDDLE JS used to upload the files:
$(document).ready(function() {
if (window.File && window.FileList &&
window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i></span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File
API")
}
});
In addition, I need to be able to upload only the following file types: .jpg, .png, .pdf, .xlsx and .docx.
Thank for any help!
If you just want to show the file names you don't need to use the img tag. You can change the code as following.
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function (e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i];
$("<span class=\"pip\">" +
"<br/><span class=\"remove\"><i class='fa fa-times'></i>"+ f.name + "</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function () {
$(this).parent(".pip").remove();
});
}
});
} else {
alert("Your browser doesn't support to File API")
}
And for the 2nd question, you can define the accepted types in your html as
<div class="file-loading">
<input type="file" id="files" name="files[]" multiple accept=".jpg,.png,.pdf,.xlsx,.docx"/>
</div>

Determine if image is duplicate

The following is the function that previews and uploads the image into the form:
//Process to upload and Preview Images being uploaded
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(a) {
var files = a.target.files,
filesLength = files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
for (var i = 0; i < filesLength; i++) {
var f = files[i];
var fileReader = new FileReader();
fileReader.fileName = files[i].name;
fileReader.onload = (function(e) {
var file = e.target;
$("<div class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br />" + "<span class=\"fontImage\">" + file.fileName + "</span><span class=\"remove\">X</span>" + "</div>").insertAfter("#files");
$('#files').val('');
/*Increment/Decrement Count of files loaded*/
var c = $(".pip").length;
if (c == 1)
$("#replaceText").text(c + " image file uploaded");
if (c > 1)
$("#replaceText").text(c + " image files uploaded");
$(".remove").on('click', function(){
$(this).parent(".pip").remove();
if($(".pip").length > 1){
c--;
$("#replaceText").text(c + " image files uploaded");
}
else if($(".pip").length == 1){
c--;
$("#replaceText").text(c + " image file uploaded");
}
else{
$("#replaceText").text("No file chosen");
}
});
/********************************/
if($(".pip").length > 1){
$("#delete_all").show();
$("#delete_all").css('margin-top',"10px");
}
else
$("#delete_all").hide();
});
fileReader.readAsDataURL(f);
}
}
}
else {
//alert("WARNING: Invalid image extension(s)");
document.getElementById("modal-title").innerHTML = "<h4>WARNING: Invalid image extension(s).</h4>";
document.getElementById("modal-body").innerHTML = "<p>Upload a image that has a valid extension(s).</p>";
document.getElementById("myform").focus();
$('#files').val('');
$("#invalidModal").modal();
return false
}
});
}
else {
//alert("Your browser doesn't support to File API.");
document.getElementById("modal-title").innerHTML = "<h4>ERROR: Does not support API</h4>";
document.getElementById("modal-body").innerHTML = "<p>Your browser doesn't support to File API. Update your current browser.</p>";
document.getElementById("myform").focus();
$("#invalidModal").modal();
return false
}
However, what I would like to achieve next is to determine whether an image that is being loaded to the form is a duplicate. What I mean is if the previous image that is already loaded to the form is being attempted to be loaded to the form again, to throw an error. Otherwise, to accept the new image. I am not sure how to achieve this. Any help would be appreciated

Jquery File Upload Add data to preview when upload is done

I'm using blueimp/jQuery-File-Upload's plugin to upload files and I'm trying (unsuccessfully) to add a data-attribute to the preview when the upload is done.
Here is the code:
$('#fileupload').fileupload({
autoUpload: true,
disableImageResize: /Android(?!.*Chrome)|Opera/.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp|doc?x|pdf|xml|psd|tif)$/i,
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-upload fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
'<div class="error"></div>' +
'<div class="progress"></div>' +
(!index && !o.options.autoUpload ?
'<button class="start" disabled>Start</button>' : '') +
(!index ? '<button class="cancel">Cancel</button>' : '') +
'</td>' +
'</div>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(file.error);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<div class="template-download fade">' +
'<span class="preview"></span>' +
'<p class="name"></p>' +
(file.error ? '<div class="error"></div>' : '') +
//'<button class="delete">Delete</button>' +
'</div>');
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.name').text(file.name);
row.find('.error').text(file.error);
} else {
row.find('.name').append($('<a></a>').text(file.name));
if (file.thumbnailUrl) {
row.find('.preview').append(
$('<a></a>').append(
$('<img>').prop('src', file.thumbnailUrl)
)
);
}
row.find('a')
.attr('data-gallery', '')
.prop('href', file.url);
row.find('button.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
}
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
}).bind('fileuploaddone', function(e, data) {
var arquivo = data.result.files[0].url;
var varCodTipoProcesso = $('.indexador-campo').data('cod-tipo-processo');
var varCodEstabelecimento = $('.estabelecimento-select').parent().children('a').children('span').data('cod-estabelecimento');
var varArrayCampos = [];
var tipos = ['jpg', 'png', 'gif', 'psd', 'bmp', 'tif', 'pdf', 'xml'];
var nome = data.result.files[0].name;
var today = new Date();
var s = today.getSeconds();
var i = today.getMinutes();
var h = today.getHours();
var dd = today.getDate();
var mm = today.getMonth();
var yyyy = today.getFullYear();
now = '' + yyyy + mm + dd + h + i + s;
var filename = now + '.' + nome.substr(nome.lastIndexOf('.')+1);
$('.indexadores-campos .row input').each(function() {
var indexadoresData = {};
indexadoresData.nomCampo = $(this).attr('name');
indexadoresData.numOrdem = $(this).data('num-ordem');
indexadoresData.valor = $(this).val();
varArrayCampos.push(indexadoresData);
});
console.log(varCodTipoProcesso)
$.getJSON('/sistema/ajax/setUploadFileJson.php', {
arquivo: arquivo,
varCodProcesso: null,
varCodTipoProcesso: varCodTipoProcesso,
varCodEstabelecimento: varCodEstabelecimento,
varCodTipoDocumento: null,
varArrayCampos: varArrayCampos,
pasta: null,
tipos: tipos,
nome: filename
}).done(function(doc) {
console.log(data.codDocumento); //there's the data I want to add to the preview
}).fail(function() {
console.log('error');
});
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>').text('Upload server currently unavailable - ' + new Date()).appendTo('#fileupload');
});
}
// Load & display existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
I managed to get the data from the server, but douldn't add it to the preview and I can't figure out how to do it. Can anybody help me on this?
The answered is already available and both will work fine.
You need to use additional plugin jquery.fileupload-ui.js as mentioned in answer (https://stackoverflow.com/a/11016888/2871356) or as mentioned in answer(https://stackoverflow.com/a/18284685/2871356) Place this inside your add(e, data) callback function, adjusting for your own html elements accordingly:
$('body').append('<img src="' + URL.createObjectURL(data.files[0]) + '"/>');

Google document preview error for large files

Whoops!
There was a problem previewing this document.
I was trying to embed google viewer to preview pdf files uploaded into my application
(function($) {
$.fn.gdocsViewer = function(options) {
var settings = {
width: '600',
height: '700'
};
if (options) {
$.extend(settings, options);
}
return this.each(function() {
var file = $(this).attr('href');
var ext = file.substring(file.lastIndexOf('.') + 1);
$(this).after(function() {
var id = $(this).attr('id');
var gdvId = (typeof id !== 'undefined' && id !== false) ? id + '-gdocsviewer' : '';
return '<div id="' + gdvId + '" class="gdocsviewer"><iframe src="https://docs.google.com/viewer?embedded=true&url=' + encodeURIComponent(file) + '" width="' + settings.width + '" height="' + settings.height + '" style="border: none;margin : 0 auto; display : block;"></iframe></div>';
})
});
};
})(jQuery);
This works fine for small size files. But showing the error when I try with files with 6mb.
Why does it happen? How to solve it?
Is there a way to limit the preview page limit?

Extension stopped working with Google Chrome manifest v2

I am developing an extension for Google Chrome that was working perfectly, but now stopped working with version 2 of the manifest.
It is giving me the following error:
Uncaught SyntaxError: Unexpected end of input
popup.js:
chrome.tabs.getSelected(null, function (aba) {
link = aba.url;
titulo = aba.title;
document.getElementById('mensagem').value = link;
});
function GrabIFrameURL(feedDescription) {
var regex = new RegExp("iframe(?:.*?)src='(.*?)'", 'g');
var matches = regex.exec(feedDescription);
var url = '';
if (matches.length == 2) {
url = matches[1];
}
var quebra = url.split("/");
return quebra[4];
}
$(document).ready(function () {
if (localStorage.nome == '' || localStorage.nome == null || localStorage.email == '' || localStorage.email == null) {
jQuery('#formulario').hide();
jQuery('#erros').html('Configure seus dados aqui');
}
jQuery("#resposta").ajaxStart(function () {
jQuery(this).html("<img src='img/loading.gif'> <b>Sugestão sendo enviada, aguarde...</b>");
});
jQuery('#submit').click(function () {
var nome = localStorage.nome;
var email = localStorage.email;
var mensagem = titulo + "\n\n<br><br>" + link;
jQuery('#formulario').hide();
jQuery.post('http://blabloo.com.br/naosalvo/mail.php', {
nome: nome,
email: email,
mensagem: mensagem
},
function (data, ajaxStart) {
jQuery('#resposta').html(data);
console.log(data);
});
return false;
});
//Listagem de posts
var bkg = chrome.extension.getBackgroundPage();
jQuery('#close').click(function () {
window.close();
});
jQuery('#markeall').click(function () {
bkg.lidoAll();
$('.naolido').attr('class', 'lido');
});
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
$('.naolido').click(function (e) {
e.preventDefault();
klicked = $(this).attr('id');
console.log(klicked);
bkg.setLido(klicked);
$(this).attr('class', 'lido');
openLink($(this).attr('href'));
});
$('.lido').click(function (e) {
openLink($(this).attr('href'));
});
var openLink = function (link) {
chrome.tabs.create({
'url': link,
'selected': true
});
window.close();
}
});
I think the problem is in this part of popup.js:
jQuery.each(bkg.getFeed(), function (id, item) {
if (item.naolido == '1')
lidoClass = 'naolido';
else
lidoClass = 'lido';
var thumb = GrabIFrameURL(item.description);
$('#feed').append('<li><a id="' + item.id + '" href="' + item.link + '" class="' + lidoClass + '"><img src="' + $.jYoutube(thumb, 'small') + '" class="' + lidoClass + '"/>' + item.title + '</a></li>');
});
You problem is actually in background.js on lines 12 and 20, you set localStorage.items to '' initially but then try to run a JSON.parse() on it later, but it's not JSON data so JSON.parse returns Unexpected end of input. And, JSON.parse isn't a function you define but a native browser function so, it shows the error as being on "line 1".
Try defining it as an empty array initially and then "pushing" to it as you are now.

Categories