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
Related
I'm working with python and flask to save my files, and to upload multiple images in js, with the preview and a delete button. When I click on the delete button, I want to delete a specific image. Currently, clicking on the delete button, deletes all.
This is the source code and I understand why the click deletes all.
let photo = document.getElementById('imgPhoto');
let file = document.getElementById('file-input');
photo.addEventListener('click', () => {
file.click();
});
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#file-input").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\">Remover imagem</span>" +"</span>").insertAfter("#file-input");
$(".remove").click(function(){
$(this).parent(".pip").remove();
document.getElementById('file-input').value = "";
});
});
fileReader.readAsDataURL(f);
}
});
}
});
The result when uploaded
I have a JQuery multi-file upload solution that requires restriction on file format and size.
Here's the JSFIDDLE, and the JS code follows below:
$(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")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
The desired outcome is to allow me to set both the file type and size that can be easily changed.
Thanks for any help!
You can set a condition right after you declare a value to your var f
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
You can also console.log(f); for more properties
Here is my version of your function:
$(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];
if(f.size > 200000 || f.type !="image/png"){
alert("File too big or not a valid Type");
$("#files").val("");
}
else{
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")
}
});
$(document).on('click', '[name=Reset]', function(){
$('.pip').remove();
})
You can check the size property of the file and the type property of the file.
var maxSize = 20000;//maximum size for the file
var acceptedTypes = ["image/png", "image/jpg"];//accepted image types
if(f.size>maxSize){
//file is too big
}
if(acceptedTypes.indexOf(f.type)<0){
//file type is not accepted
}
JSFiddle: https://jsfiddle.net/ordmsw8p/
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>
I'm using a input type file multiple to update some pictures. Before upload, the page shows a miniature of each picture. I would like to do a remove link to each picture, and when the user clicks, the picture disapear and the file is removed from input.
I try to use this code below:
HTML:
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" />
<div id="midiaDigital"></div>
Javascript:
$(document).ready(function() {
$("#midiasUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#midiaDigital");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$(image_holder).append('<div class="form-group row">' +
'<div>' +
'<div class="col-md-6">' +
'<img src="' + e.target.result + '" class="thumb-image img-responsive">' +
'<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' +
'Remover' + //add input box
'</div>' +
'</div>' +
'</div>');
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("O browser não suporta upload de arquivos.");
}
} else {
alert("Formato de arquivo inválido");
}
});
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
})
});
Using this code, the "preview" pictures appear with the "remove" link. When I click in the "remove", the preview picture are deleted, but the file continues selected. What should I do?
You can do it simply via jQuery in one line: $('#midiasUpload').val('');. It resets input value. Here is the snippet:
function select(el) {
img = el;
}
var img;
var input;
$(document).ready(function() {
$("#midiasUpload").on('change', function() {
var countFiles = $(this)[0].files.length;
input = $(this)[0];
console.log('Input value after upload: ', input.value)
var imgPath = input.value;
img = imgPath;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#midiaDigital");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function(e) {
$(image_holder).append('<div class="form-group row">' +
'<div>' +
'<div class="col-md-6">' +
'<img src="' + e.target.result + '" class="thumb-image img-responsive" onclick="select($(this))">' +
'<input type="text" class="form-control input-sm" name="midiaDigitals[' + i + '].legenda" placeholder="Digite a descrição da mídia digital"/>' +
'Remover' + //add input box
'</div>' +
'</div>' +
'</div>');
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("O browser não suporta upload de arquivos.");
}
} else {
alert("Formato de arquivo inválido");
}
});
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
img.val = '';
input.value = null;
console.log('Input value after remove: ', input.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="midiasUpload" multiple="multiple" type="file" name="midias" accept="image/x-png,image/gif,image/jpeg" />
<div id="midiaDigital" style="margin-bottom: 100px;"></div>
Please change this code inside $(image_holder).append( function
'Remover' + //add input box
This code works after clicking on remove_field1
$(midiaDigital).on("click",".remove_field1", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove();
var deletedId=$(this).prop("data-id");
var names = [];
for (var i = 0; i < $("#midiasUpload").get(0).files.length; ++i) {
if(deletedId==i){}else{ names.push($("#midiasUpload").get(0).files[i].name); }
}
$("#midiasUpload").val(names);
});
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.