Inside javascript need to change value of a hidden input field - javascript

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

Related

Change Event is not working on input field

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>

div used for image display causing difficulties while uploading file;

Here i have a image upload mechanism. It's purpose is to accept an image and display it in a div with id=imageholder . My problem is if i have this image holder div inside my form , it gives upload error (4) . So i get an empty $_FILES array. But if i omit it i get a populated $_FILES array .But i need that div inside the form for design purpose. How i can escape this situation .
with imagehoder div inside form:
without imageholder div :
code may seem long . But none of it is related to the question. It is generally for validating the mime type
full code :
<?php print_r($_FILES);?>
<html>
<body>
<form method='post' enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id='photouploder'>
<div id='imagehoder'></div> // creating problem
<div class="inputWrapper">upload image
<input class="fileInput" id='up' type="file" name="image"/>
</div>
</div>
<input type='submit' value='submit'>
</form>
<script>
var imageholder=document.getElementById('imageholder');
function getBLOBFileHeader(url, blob, callback,callbackTwo) {
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);
}
var imgtype= callback(url, header);// headerCallback
callbackTwo(imgtype,blob)
};
fileReader.readAsArrayBuffer(blob);
}
function headerCallback(url, headerString) {
var info=getHeaderInfo(url, headerString);
return info;
}
function getTheJobDone(mimetype,blob){
var mimearray=['image/png','image/jpeg','image/gif'];
console.log('mimetype is :'+mimetype);
if(mimearray.indexOf(mimetype) !=-1){
printImage(blob);
}else{
document.getElementById('up').value='';
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
console.log('you can not upload this file type');
}
}
function remoteCallback(url, blob) {
getBLOBFileHeader(url, blob, headerCallback,getTheJobDone);
}
function printImage(blob) {
// Add this image to the document body for proof of GET success
var fr = new FileReader();
fr.onloadend = function(e) {
var img=document.createElement('img');
img.setAttribute('src',e.target.result);
img.setAttribute('style','width:100%;height:100%;');
imageholder.appendChild(img);
};
fr.readAsDataURL(blob);
}
function mimeType(headerString) {
switch (headerString) {
case "89504e47":
type = "image/png";
break;
case "47494638":
type = "image/gif";
break;
case "ffd8ffe0":
case "ffd8ffe1":
case "ffd8ffe2":
type = "image/jpeg";
break;
default:
type = "unknown";
break;
}
return type;
}
function getHeaderInfo(url, headerString) {
return( mimeType(headerString));
}
// Check for FileReader support
function fileread(event){
if (window.FileReader && window.Blob) {
/* Handle local files */
var mimetype;
var mimearray=['image/png','image/jpeg','image/gif'];
var file = event.target.files[0];
if(mimearray.indexOf(file.type)===-1 || file.size >= 2 * 1024 * 1024){
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
console.log("you can't upload this file type");
file=null;
return false;
}else{
while (imageholder.firstChild) {
imageholder.removeChild(imageholder.firstChild);
}
document.getElementById('up').value='';
remoteCallback(file.name, file);
}
}else {
// File and Blob are not supported
console.log('file and blob is not supported');
} /* Drakes, 2015 */
}
document.getElementById('up').addEventListener('change',fileread,false);
</script>
</body>
</html>
First of all: HTML attribute values should always be encapsulated in double quotes.
Second, this is a correct example of reading files using html5 API like you tried:
(Also check the documentation for it: https://developer.mozilla.org/en-US/docs/Web/API/FileReader)
window.onload = function() {
var fileInput = document.getElementById('up');
var fileDisplayArea = document.getElementById('imagehoder');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var imageType = /image.*/;
if (file.type.match(imageType)) {
var reader = new FileReader();
reader.onload = function(e) {
fileDisplayArea.innerHTML = "";
var img = new Image();
img.src = reader.result;
fileDisplayArea.appendChild(img);
}
reader.readAsDataURL(file);
} else {
fileDisplayArea.innerHTML = "File not supported!"
}
});
}
<body>
<form method="post" enctype='multipart/form-data' action="<?php echo $_SERVER['PHP_SELF'] ?>">
<div id="photouploder">
<div id="imagehoder"></div>
<div class="inputWrapper">upload image
<input class="fileInput" id="up" type="file" name="image" />
</div>
</div>
<input type="submit" value="submit">
</form>
</body>
I'm not sure about the 'design purpose' in your question. If the 'design purpose' means UI design (CSS related), then probably this reason doesn't stand since they are totally irrelevant.
Also, the file upload technology is very mature now. There are bunches of open source implements in all languages and are well-tested and easy-to-use I highly recommend you to take a look at them before implementing it yourself.

replace XMLHttpRequest in javascript

I used to read my local files using XMLHttpRequest.
function getData(fileName)
{
var filePath = fileName;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filePath, false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
fileName starts with "C://..." and my program works on browser with address "file:///...".
But, without "--allow-file-access-from-files" tag, my code doesn't work on Chrome. And also it doesn't work on IE and Firefox without changing some security options.
So, I tried to jquery API like this,
function getData(fileName)
{
var filePath = fileName;
var fileContent;
$.ajax({
type: "GET",
url: filePath
})
.done(function(data) {
alert(data);
fileContent = data;
});
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
The Problem also occurs. I think Same-origin policy prevents it.
Can anyone give me some suggestions for me to access local files without changing security options? Should I use some plug-ins to solve this?
Please let me know.
Thank you.
If you can use <input type="file"> to select files, then the solution is:
HTML:
<form action="">
<input type="file" id="file-input" multiple="multiple" accept="image/jpeg" />
</form>
JS:
var fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', function(event) {
var files = fileInput.files;
if (files.lenght == 0) {
return;
}
for(var i = 0; i < files.length; i++) {
readFile(files[i]);
}
fileInput.value = "";
}, false);
var readFile= function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
// now, load the data into some element
// if this is image, you can do this:
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image);
};
reader.readAsDataURL(file);
};
Also, discover the FileReader API to find out, how you can use it otherwise, as it has more methods to read data.

Dropzone.js to get file URL

I have this function which generates the File URL using createobjectURL and works when I use the normal input file tag.
I am trying to implement the same using dropzone.js but when I drop the file it starts
showing the upload progress bar although I haven't defined any action.
How can i obtain the URL using dropzone.js?
Javascript
function localFileVideoPlayerInit(win) {
var URL = win.URL || win.webkitURL,
displayMessage = (function displayMessageInit() {
return function displayMessage() {
alert("error");
};
}()),
playSelectedFile = function playSelectedFileInit(event) {
var file = this.files[0];
var type = file.type;
var videoNode = document.querySelector('video');
var canPlay = videoNode.canPlayType(type);
canPlay = (canPlay === '' ? 'no' : canPlay);
if (canPlay === 'no') {
displayMessage();
}
}
};
var fileURL = URL.createObjectURL(file);
videoNode.src = fileURL;
},
inputNode = document.querySelector('input');
if (!URL) {
displayMessage('Your browser is not ' + 'supported!', true);
return;
}
inputNode.addEventListener('change', playSelectedFile, false);
}
HTML
<form action="" class="dropzone">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
Seems you would have to reference the variable fileURL, and use javascript to dynamically set the action of the form.

File type validation with JavaScript

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

Categories

Resources