It keeps displaying undefined for file name - javascript

I trying to display the name of the file after the user has uploaded it. The file uploads successfully but in the javascript it keeps displaying the message below:
The file (undefined) was uploaded successfully!
It keeps displaying undefined when it should display the filename. Why is this? At the moment what is happening is that wen the user uploads the file, the files is uploaded into the "ImageFiles" folder, when uploading is finsihed the javascript function below displays the message to state the name of the file which has been successfully uploaded.
Below is the code which displays the file name and message after uploading:
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
localStorage["fname"] = files[0].name; //save the name for future use
}
$('.fileImage').bind('change', handleFileSelect, false);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
localStorage["fname"] = undefined; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is form:
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
</form>

Try this:
var fileName;
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
fileName = files[0].name; //save the name for future use
}
$('.fileImage').bind('change', handleFileSelect, false);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+fileName+') was uploaded successfully!</span><br/><br/>';
fileName = ""; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}

Not tested, but try using getItem/setItem and see if that changes anything!
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
console.log(files[0].name); //see if a name really exists, or if something is wrong outside this function?
localStorage.setItem("fname", files[0].name); //save the name for future use
}
$('.fileImage').on('change', handleFileSelect);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage.getItem("fname")+') was uploaded successfully!</span><br/><br/>';
localStorage.setItem("fname", ""); //remove the temporary variable
} else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}

Related

Check file extension and alert user if isn't image file using javascript

When i upload multiple images and one of them which is not valid extension and message should be shown File type is not valid and when I upload images one by one it works perfect please help me how can resolve that ? thank u
javascript
$("input[type=file]").on('change', function(){
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
});
With the multiple attribute added to the input HTML tag, iterate the files property on the input element in the change event listener.
document.addEventListener('DOMContentLoaded', function () {
document.querySelector("input").addEventListener("change", changeHandler);
});
function changeHandler() {
const validFileExtensions = ['jpeg', 'jpg', 'png'];
// 'this' refers to the 'input' HTML element
// Assigning 'this' to the 'element' variable is not
// necessary but assigned here for code readability.
let element = this;
// Check if the element has a FileList before checking each file
if (element.files && element.files.length) {
for (i = 0; i < element.files.length; i++) {
const file = element.files[i];
const filename = file.name;
const extension = filename.split('.').pop();
if (validFileExtensions.includes(extension)) {
console.log("VALID file -> " + filename);
}
else {
console.log("INVALID file -> " + filename);
}
}
}
}
<input type="file" multiple />
Applying the code above to your jQuery code:
$("input[type=file]").on('change', function() {
//Get uploaded file extension
var extension = $(this).val().split('.').pop().toLowerCase();
// Create array with the files extensions that we wish to upload
var validFileExtensions = ['jpeg', 'jpg', 'png'];
//Check file extension in the array.if -1 that means the file extension is not in the list.
if ($.inArray(extension, validFileExtensions) == -1) {
$('#filetype').text("File type is not valid").show();
$('#btnSubmit').prop('disabled', true);
}
// Check if the element has a FileList before checking each file
if (this.files && this.files.length) {
var message = "";
for (i = 0; i < this.files.length; i++) {
var file = this.files[i];
var filename = file.name;
var extension = filename.split('.').pop();
if (!validFileExtensions.includes(extension)) {
message += filename + " is not a valid file type. ";
}
}
if (message !== "") {
$('#filetype').text(message).show();
$('#btnSubmit').prop('disabled', true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="fileInput" multiple>
<span id="filetype"></span>
<button type="submit">Upload</button>
const fileInput = document.querySelector('input[type="file"]');
const submitBtn = document.querySelector('button[type="submit"]');
submitBtn.disabled = true;
fileInput.addEventListener('change', () => {
const fileName = fileInput.value;
const fileType = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if (fileType !== 'jpg' && fileType !== 'jpeg' && fileType !== 'png' && fileType !== 'gif') {
alert('File is not an image');
fileInput.value = '';
submitBtn.disabled = true; // Disable the submit button
} else {
submitBtn.disabled = false; // Enable the submit button
}
});
.fileInput{
text-align:center;
margin-top:10%;
}
<div class="fileInput">
<input type="file" id="fileInput">
<button type="submit">Upload</button>
</div>

Call a certain URL on HTML5 upload

Alright, So I have this script that uploads a file on drag and drop from the browser using HTML5.
$(function(){
var dropbox = $('#dropbox'),
message = $('.message', dropbox);
dropbox.filedrop({
// The name of the $_FILES entry:
paramname:'pic',
maxfiles: 50,
maxfilesize: 50,
url: 'post_file.php',
uploadFinished:function(i,file,response){
$.data(file).addClass('done');
// response is the JSON object that post_file.php returns
},
error: function(err, file) {
switch(err) {
case 'BrowserNotSupported':
showMessage('Your browser does not support HTML5 file uploads!');
break;
case 'TooManyFiles':
alert('Too many files! Please select 20 at most! (configurable)');
break;
case 'FileTooLarge':
alert(file.name+' is too large! Please upload files up to 10mb (configurable).');
break;
default:
break;
}
},
//// Called before each upload is started
// beforeEach: function(file){
// if(!file.type.match(/^image\//)){
// alert('Only images are allowed!');
//
// // Returning false will cause the
// // file to be rejected
// return false;
// }
// },
uploadStarted:function(i, file, len){
createImage(file);
},
progressUpdated: function(i, file, progress) {
$.data(file).find('.progress').width(progress);
}
});
var template = '<div class="preview">'+
'<span class="imageHolder">'+
'<img />'+
'<span class="uploaded"></span>'+
'</span>'+
'<div class="progressHolder">'+
'<div class="progress"></div>'+
'</div>'+
'</div>';
function createImage(file){
var preview = $(template),
image = $('img', preview);
var reader = new FileReader();
image.width = 100;
image.height = 100;
reader.onload = function(e){
// e.target.result holds the DataURL which
// can be used as a source of the image:
image.attr('src',e.target.result);
};
// Reading the file as a DataURL. When finished,
// this will trigger the onload function above:
reader.readAsDataURL(file);
message.hide();
preview.appendTo(dropbox);
// Associating a preview container
// with the file, using jQuery's $.data():
$.data(file,preview);
}
function showMessage(msg){
message.html(msg);
}
});
It runs on with the following post_file.php
<?php
// If you want to ignore the uploaded files,
// set $demo_mode to true;
$demo_mode = false;
$upload_dir = 'uploads/';
//$allowed_ext = array('jpg','jpeg','png','gif','doc','docx','pdf','xls','xlsx','pptx','ppt','rtf','txt','mp4','css','rar','zip','exe','mp3','wav');
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
exit_status('Error! Wrong HTTP method!');
}
if(array_key_exists('pic',$_FILES) && $_FILES['pic']['error'] == 0 ){
$pic = $_FILES['pic'];
//if(!in_array(get_extension($pic['name']),$allowed_ext)){
// exit_status('Only '.implode(',',$allowed_ext).' files are allowed!');
//}
if($demo_mode){
// File uploads are ignored. We only log them.
$line = implode(' ', array( date('r'), $_SERVER['REMOTE_ADDR'], $pic['size'], $pic['name']));
file_put_contents('log.txt', $line.PHP_EOL, FILE_APPEND);
exit_status('Uploads are ignored in demo mode.');
}
// Move the uploaded file from the temporary
// directory to the uploads folder:
if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
exit_status('File was uploaded successfuly!');
}
}
exit_status('Something went wrong with your upload!');
// Helper functions
function exit_status($str){
echo json_encode(array('status'=>$str));
exit;
}
function get_extension($file_name){
$ext = explode('.', $file_name);
$ext = array_pop($ext);
return strtolower($ext);
}
?>
Now the problem is I have a certain JSON url that when I open it sends a text message to a certain number. I'm trying to append that URL somewhere in the script so that it runs that url everytime an upload is made.
Any ideas?
$URL = "http://www.api.com/api.php?data=mydata";
$data = file_get_contents($URL);
This solves it.

Trying to upload images without refreshing page with javascript, not working

I am trying to upload images to my server via an html-form without refreshing the page. My problem is the files arent getting uploaded and I cant figure out why.
Javascript code:
function uploadFiles(event) {
var fileSelect = document.getElementById('file');
var files = fileSelect.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.type.match('image.*')) {
alert("File: " + file.name + " is not an image and will not be uploaded.");
continue;
}
formData.append('images[]', file, file.name);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '../htdocs/Php/upload_file.php', true);
xhr.onload = function () {
if (xhr.status === 200) {
// File(s) uploaded.
alert('files uploaded');
} else {
alert('An error occurred!');
}
};
xhr.send(formData);
}
HTML code:
<form action="../htdocs/Php/upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="images[]" id="file" onchange="uploadFiles()" multiple required />
</form>
PHP code:
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
if (!file_exists("../UploadedImages/" . $_FILES["images"]["name"][$id])) {
move_uploaded_file($_FILES["images"]["name"][$id], "../UploadedImages/" . $_FILES["images"]["name"][$id]);
}
}
Looks like your JavaScript is correct, but your PHP needs some attention. I modified your php so that it first check to see if $_FILES were passed. Then where you had some incorrect logic was in your !file_exists() statement and how you move and check the file name.
To check if a file exists, and to move the file you need to use $_FILES['images']['tmp_name']. The 'name' attribute is just the name of the file uploaded, not the physical file uploaded to the browser.
To really test your code, use firebug and look at the console. It should return a line that you can expand and look at what was posted and what was returned.
Here is an example, the following code i gave you returns this:
C:\filepath\binaries\tmp\phpDB53.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB54.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB55.tmp Was Succesuflly uploaded
C:\filepath\binaries\tmp\phpDB56.tmp Was Succesuflly uploaded
NOTE: Double check that the files paths are absolutely correct. When checking firebug console, the php file will also return file errors as well, given that you have php error reporting on.
//Check if files were passed through to your ajax page
if(isset($_FILES)) {
$numberOfFiles = count($_FILES['images']['name']);
for($id = 0; $id < $numberOfFiles; $id++)
{
if (file_exists($_FILES["images"]["tmp_name"][$id])) {
move_uploaded_file($_FILES["images"]["tmp_name"][$id], $_FILES["images"]["name"][$id]);
echo $_FILES["images"]["tmp_name"][$id] . " Was Succesuflly uploaded \r\n ";
} else {
echo "file didnt exists " . $_FILES["images"]["tmp_name"][$id] . "\r\n ";
}
}
} else {
//No Files were passed through
echo "no files passed through";
}
exit();
Hopefully that answers your question.

Reset fileupload control from javascript

I have a ASP website page where i have a upload control added
<asp:FileUpload ID="FileUpload1" runat="server"
BorderStyle="None" Width="215px" onchange="return checkfile();" style="margin-left: 14px" BackColor="#F0F0F0" />
From javascript i am validating the file which will be uploaded. If it is of type .exe then I will not allow to upload and give a message. if not i will display the file name in label "lblFileName" . But the problem if error(in case file is exe) then i want to reset the upload control(FileUpload1) . Now it will show only message but allows form to submit along with the .exe file.So how I can reset it?
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = "you cannot attach exe file";
return false;
}
else {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
}
}
Your code is the problem onchange="return checkfile();"
And your function should look like
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('lblFileName').innerHTML = "you cannot attach exe file";
document.getElementById("FileUpload1").value='';
return false;
}
else {
document.getElementById('lblFileName').innerHTML = filename;
}
}
Return will disallow file to put in your file upload control so this will solve your problem
Please check demo here
I am doing it this way using jquery:
$(function () {
$('<%= fileUploadCV.ClientID %>').change(function () {
//because this is single file upload I use only first index
var f = this.files[0]
//here I check if the file size is bigger than 8 MB (numbers below are in bytes)
if (f.size > 8388608 || f.fileSize > 8388608)
{
//show an alert to the user
alert("Allowed file size exceeded. (Max. 8 MB)")
//and RESET file upload control
this.value = null;
}
})
});

I keep getting undefined below

I trying to display the name of the file after the user has uploaded it. The file uploads successfully but in the javascript it keeps appending in the list 'undefined'. Why does it keep displaying 'undefined' and not the name of the file uploaded from the file input??:
Below is the code which displays the file name and message after uploading:
function stopImageUpload(success){
function handleFileSelect(evt) {
var files = evt.target.files;
localStorage["fname"] = files[0].name; //save the name for future use
}
$('.fileImage').bind('change', handleFileSelect, false);
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
localStorage["fname"] = undefined; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
Below is form:
<form action='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='stopImageUpload(this);' class='imageuploadform' >
<p>Image File: <input name='fileImage' type='file' class='fileImage' />
<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' />
</p>
<ul class='list'></ul>
</form>
Try breaking apart your functions. Bind the change event outside of the function that handles the form submit.
$(document).ready(function(){
$('.fileImage').bind('change', handleFileSelect, false);
});
function handleFileSelect(evt) {
var files = evt.target.files;
localStorage["fname"] = files[0].name; //save the name for future use
}
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file ('+localStorage["fname"]+') was uploaded successfully!</span><br/><br/>';
localStorage["fname"] = undefined; //remove the temporary variable
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}

Categories

Resources