I'm trying to debug and find the error, why Change Event is not working on input field. so i have put breakpoint on change event of jquery while debugging but it skip that .i am not able to find why it is not stopping at breakpoint for debugging.
html part which is generated dynamically only a part is shown here.
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
$("#mainTbl").append(p);
script
<script type="text/javascript">
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
//tried all three trick to envoke change function but not work
//$('input[name=flImage]').change(function () {
$("<input type='file' name='flImage' ID='flImage'/>").change(function () {
//$("input[name=flImage]").on("change", function(){
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
</script>
After show many advice from comment i'm trying like this to access input element
is it ok :div.main main-raised > div#pdfFormInsideL1 > table#mainTbl > tbody >tr>'input[name=flImage]
image given below
var p = $('<input type="file" ID="flImage" name="flImage" runat="server" />');
$("#mainTbl").append(p);
$(function () {
var reader = new FileReader();
var fileName;
var contentType;
$("input[name=flImage]").on("change", function(){
if (typeof (FileReader) != "undefined") {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
fileName = file[0].name;
contentType = file[0].type;
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainTbl"></div>
Related
I'm trying to pass an image in a base64 format, however, the client returns a 400 Bad Request when the byte size exceeds somewhere around 280000-290000. Is there any way to "force" the upload despite this?
Here is the relevant code:
View:
<div class="span4 target">
<label asp-for="T_Image1" class="control-label"></label>
<input id="Image1" asp-for="T_Image1" type="hidden" class="target"/>
<span asp-validation-for="T_Image1" class="text-danger"></span>
</div>
<input type="submit" value="Create" class="btn btn-primary" />
Javascript:
(function ($) {
var defaults;
$.event.fix = (function (originalFix) {
return function (event) {
event = originalFix.apply(this, arguments);
if (event.type.indexOf("paste") === 0) {
event.clipboardData = event.originalEvent.clipboardData;
}
return event;
};
})($.event.fix);
defaults = {
callback: $.noop,
matchType: /image.*/
};
return ($.fn.pasteImageReader = function (options) {
if (typeof options === "function") {
options = {
callback: options
};
}
options = $.extend({}, defaults, options);
return this.each(function () {
var $this, element;
element = this;
$this = $(this);
return $this.bind("paste", function (event) {
var clipboardData, found;
found = false;
clipboardData = event.clipboardData;
return Array.prototype.forEach.call(clipboardData.types, function (type, i) {
var file, reader;
if (found) {
return;
}
if (
type.match(options.matchType) ||
clipboardData.items[i].type.match(options.matchType)
) {
file = clipboardData.items[i].getAsFile();
reader = new FileReader();
reader.onload = function (evt) {
return options.callback.call(element, {
dataURL: evt.target.result,
event: evt,
file: file,
name: file.name
});
};
reader.readAsDataURL(file);
return (found = true);
}
});
});
});
});
})(jQuery);
var dataURL, filename;
$("html").pasteImageReader(function (results) {
filename = results.filename, dataURL = results.dataURL;
$data.text(dataURL);
$size.val(results.file.size);
$type.val(results.file.type);
var img = document.createElement("img");
img.src = dataURL;
var w = img.width;
var h = img.height;
$width.val(w);
$height.val(h);
var target = document.getElementsByClassName("active");
var element = target.item(0);
//sets value of hidden field to base64 for the controller
element.firstElementChild.nextElementSibling.value = dataURL;
element.files = results.file;
return $(".active")
.css({
backgroundImage: "url(" + dataURL + ")"
});
});
Please note, I'm not very good at Javascript, I'm not quite sure what I need and what I do not. Please forgive.
this is how to change file size limit
<configuration>
<system.web>
<httpRuntime maxRequestLength="xxx" />
</system.web>
</configuration>
edit
change xxx to desired number
edit 2
place it in correct order in web config basically find configuration tag in web config the in it find system.web if it existed and add the httpruntime line otherwise add entire systen.web tag with httpruntime in it
have multiple file inputs in form now I have to check for each file input that zip file doesn't contain any invalid files (doc, docx and pdf only allow).
I wrote
<script src="https://code.jquery.com/jquery-2.2.1.js" integrity="sha256-eNcUzO3jsv0XlJLveFEkbB8bA7/CroNpNVk3XpmnwHc=" crossorigin="anonymous"></script>
<script type="text/javascript" src="/js/zip.js"/>
<script type="text/javascript" src="/js/inflate.js"/>
<script type="text/javascript" src="/js/deflate.js"/>
<script type="text/javascript" src="/js/z-worker.js"/>
<script type="text/javascript">
$(document).ready(function () {
if((window.location.href.indexOf("LibraryItemUpload`1&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1) || (window.location.href.indexOf("LibraryItemUpload%601&ParentId=7d428470-2234-41c0-85f4-a512d51198c6") > -1))
{
$("input:file").change(function () {
var regex=new RegExp("^[A-Za-z0-9 ]+$");
var file=this.files[0];
var key = this.value;
var ze = key.split('\\').pop();
var filename = ze.split('.')[0];
var extension=key.split('.').pop().trim().toLowerCase();
if(extension == 'zip')
{
zip.createReader(new zip.BlobReader(file), function(reader) {
// get all entries from the zip
reader.getEntries(function(entries) {
if (entries.length) {
// get first entry content as text
entries[0].getData(new zip.TextWriter(), function(text) {
// text contains the entry data as a String
console.log(text);
// close the zip reader
reader.close(function() {
// onclose callback
});
}, function(current, total) {
// onprogress callback
});
}
});
}, function(error) {
});
}
if (!regex.test(filename)) {
alert('Please do not use special characters in file name please rename file name and upload it again.');
location.reload();
}
else {
return true;
}
});
}
});
</script>
and written code to read file name from zip.js but flow doen't go in zip.createReader function.
please suggest me if another javascript available for read zip file, I just want entries object to read files name.
function readEntries(entries) {
var entryLength = entries.length;
for (i = 0; i < entryLength; i++) {
var entry = entries[i];
var fileName = entry.filename.substring(entry.filename.lastIndexOf("/") + 1); //if inside folder
var ext = fileName.split(".").pop().toLowerCase();
if (ext.toUpperCase() == 'DOC' || ext.toUpperCase() == 'PDF' ||
ext.toUpperCase() == 'DOCX') {
//logic
}
}
}
zip.useWebWorkers = false;//explicitly include (required) zip-workers ['zip.js','zip-fs.js','z-worker.js','inflate.js','deflate.js']
var fileInput = document.getElementById("zipfile");//Input File
fileInput.addEventListener('change', function(event) {
zip.createReader(new zip.BlobReader(fileInput.files[0]), function(zipReader) {
zipReader.getEntries(readEntries);
}, function (error) {
console.log(error);
});
});
I have not tested this piece of code, but I have used similar logic before.
Consider this:
<input type="file" id="filePicker">
<script>
document.getElementById('filePicker').onchange = function() {
alert('Hi!');
};
</script>
Even if you choose the same file and the filePicker value doesn't change, you'll see the alert box in Firefox. Any solutions?
Use a temporary variable to hold the name of the filename that you can check the next time you select a file:
var filenameTemp = null;
document.getElementById('filePicker').onchange = function(e) {
var filename = e.target.value;
if (filename !== filenameTemp) {
filenameTemp = filename;
console.log('OK');
// other code
} else {
console.log('Not OK')
}
};
DEMO
Run the snippet below. It will say "New File!" when there is a new file for both Chrome and Firefox.
var previousFile = {};
function isSame(oldFile, newFile) {
return oldFile.lastModified === newFile.lastModified &&
oldFile.name === newFile.name &&
oldFile.size === newFile.size &&
oldFile.type === newFile.type;
}
document.getElementById('filePicker').onchange = function () {
var currentFile = this.files[0];
if (isSame(previousFile, currentFile) === false) {
alert('New File!');
previousFile = currentFile;
}
};
<input type="file" id="filePicker">
I have tried several things but its not working. Can someone help me to understan the problem with this code. This is a file upload script. I'm using it with codeigniter. My requirement is after user upload files(works right now) those file names should added to the hidden field.
<input type="hidden" name="extra_images" value="" />
<label for="deal_duration">Deal Extra Images</label>
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop files here to upload</div>
<script type="text/javascript">
(function(){
var dropzone = document.getElementById('dropzone');
var uploads = new Array();
var hidden = document.getElementsByName('extra_images');
var displayUploads = function(data){
var uploads = document.getElementById('uploads'),
anchor,
x;
var errors = new Array();
for(x=0;x<data.length;x=x+1){
if((typeof(data[x].file) === 'undefined') && (typeof(data[x].error) != 'undefined'))
{
errors.push(data[x].error);
}
else
{
anchor = document.createElement('a');
anchor.href = 'http://localhost/project-cg/'+ data[x].file;
anchor.innerText = data[x].name;
anchor.target = '_blank';
uploads.appendChild(anchor);
uploads.push(data[x].data[x].name);
}
}
if(errors.length > 0){
alert(errors);
}
if(uploads.length > 0){
//This is what I tried so far.But its not working
hidden.value = uploads.join("|");
}
}
var upload = function(files){
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x=0;x<files.length;x=x+1){
formData.append('file[]',files[x]);
}
xhr.onload = function(){
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post','http://localhost/project-cg/image_upload');
xhr.send(formData);
}
dropzone.ondrop = function(e){
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
}
dropzone.ondragover = function(){
this.className = 'dropzone dragover';
return false;
}
dropzone.ondragleave = function(){
this.className = 'dropzone';
return false;
}
}());
</script>
After I post data hidden field is still empty.
I saw your error:
You have 2 variables called uploads. One is an instance of the div and the other is the array.
What you are basically doing is assigning it a new type whenever you launch the function and in the end you have no array to pull data from. Try renaming them.
var hidden = document.getElementsByName('extra_images'); // returns a list of nodes
Try something like this :
hidden[0].value = uploads.join("|");
see mdn
I have a question regarding to JavaScript validation. I am validaing the <input type="file"> whenever my scripts runs, it validates but also the action page is called. I want to stop the action page until the validation is complete. Here is my code, any help will be awesome. Regards
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image Uploading</title>
</head>
<body>
<form name="xx" action="server.php" method="post" enctype="multipart/form-data" onsubmit="Checkfiles(this)">
<input type="file" name="file_uploading" id="filename">
<input type="submit" value="Submit" name="uploadfile">
</form>
<form name="view" method="post">
View your uploaded Images
</form>
</body>
</html>
<script type="text/javascript">
function Checkfiles() {
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext =="GIF" || ext=="gif") {
return true;
} else {
alert("Upload Gif Images only");
return false;
}
}
</script>
var fname = "the file name here.ext";
var re = /(\.jpg|\.jpeg|\.bmp|\.gif|\.png)$/i;
if (!re.exec(fname)) {
alert("File extension not supported!");
}
File Extension Validation through javascript
function ValidateExtension() {
var allowedFiles = [".doc", ".docx", ".pdf"];
var fileUpload = document.getElementById("fileUpload");
var lblError = document.getElementById("lblError");
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(" + allowedFiles.join('|') + ")$");
if (!regex.test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
lblError.innerHTML = "";
return true;
}
onclick event of submit button call this javascript function.
With the help of ID = lblError , print the error message in html section.
You can use the File Api to test for magic number. Maybe take a look at this answer for other ideas about the validation. More reliable than the file extension check.
The return value of the submit handler affects the submission.
onsubmit="return Checkfiles();"
This is basically saying:
form.onsubmit = function () { return Checkfiles(); };
In general, you can use JavaScript some() method for that.
function isImage(icon) {
const ext = ['.jpg', '.jpeg', '.bmp', '.gif', '.png', '.svg'];
return ext.some(el => icon.endsWith(el));
}
const fname = "filename.ext";
if (!isImage(fname)) {
console.log("File extension not supported!");
}
You need to return CheckFiles()
Upload bulk data through excel sheet(.csv)
$("form").submit(function(){
var val = $(this).val().toLowerCase();
var regex = new RegExp("(.*?)\.(csv)$");
if(!(regex.test(val))) {
$(this).val('');
alert('Only csv file can be uploaded');
return false;
}
});
var _URL = window.URL || window.webkitURL;
$("input[type=file]").change(function(e) {
var file;
if ((file = this.files[0])) {
var img = new Image();
img.onload = function () {
// do to on load
};
img.onerror = function () {
alert("valid format " + file.type);
};
img.src = _URL.createObjectURL(file);
}
});
The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.
HTML
<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>
<!-- Image preview -->
<div id="imagePreview"></div>
JavaScript
function fileValidation(){
var fileInput = document.getElementById('file');
var filePath = fileInput.value;
var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
if(!allowedExtensions.exec(filePath)){
alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
fileInput.value = '';
return false;
}else{
//Image preview
if (fileInput.files && fileInput.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
};
reader.readAsDataURL(fileInput.files[0]);
}
}
}
fileValidation()
> html
<input type="file" id="userfile" name="userfile" value="" class="form-control userfile" required>
> javascript
$(document).on('change', '.userfile', function (e) {
e.preventDefault();
const thisValue = $(this).val().split('.').pop().toLowerCase();
const userFile = [thisValue];
// Allowing file type
const validFile = ['csv', 'xlsx'];
// const intersection = validFile.filter(element => userFile.includes(element));
// if(intersection == ''){
// $(this).val('');
// alert('Please Select ' + validFile + ' file');
// return false;
// }
// Allowing file type
const allowedExtensions = /(\.csv|\.xlsx)$/i;
if (!allowedExtensions.exec($(this).val())) {
$(this).val('');
alert('Please Select ' + validFile + ' file');
return false;
}
});