its me again. Im currently trying to build an multiple file uploader for my site but dont know how to get/handle all files. I think showing you the code first will be a better explanation:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>NDSLR - Demo Upload</title>
</head>
<body>
<script type="text/javascript">
function fileChange()
{
//FileList Objekt aus dem Input Element mit der ID "fileA"
var fileList = document.getElementById("fileA").files;
//File Objekt (erstes Element der FileList)
var file = fileList[0];
//File Objekt nicht vorhanden = keine Datei ausgewählt oder vom Browser nicht unterstützt
if(!file) {
return;
}
var x = substr(file.name, -4);
document.getElementById("status").innerHTML = x;
/*
if (x != ".pdf") {
document.getElementById("fileA").files = null;
file = null;
fileList = null;
alert("Wrong Data");
return;
} */
document.getElementById("fileName").innerHTML = 'Dateiname: ' + file.name;
document.getElementById("fileSize").innerHTML = 'Dateigröße: ' + file.size + ' B';
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
var client = null;
function uploadFile()
{
//Wieder unser File Objekt
for(i=0;i < document.getElementById("fileA").files; i++) {
var file = document.getElementById("fileA").files[i];
//FormData Objekt erzeugen
var formData = new FormData();
//XMLHttpRequest Objekt erzeugen
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
//Fügt dem formData Objekt unser File Objekt hinzu
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
}
}
function uploadAbort() {
if(client instanceof XMLHttpRequest)
//Briecht die aktuelle Übertragung ab
client.abort();
}
</script>
<form action="" method="post" enctype="multipart/form-data">
<input name="file[]" type="file" multiple="multiple" id="fileA" onchange="fileChange();"/>
<input name="upload[]" value="Upload" type="button" accept=".dem" onclick="uploadFile();" />
<input name="abort" value="Abbrechen" type="button" onclick="uploadAbort();" />
</form>
<div id="status"></div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<progress id="progress" style="margin-top:10px"></progress> <span id="prozent"></span>
</div>
</body>
</html>
So this is my HTML Code and following up my upload.php:
<?php
if (isset($_FILES['datei']))
{
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.$_FILES['datei']['name']);
}
?>
My Problem currently is, that i dont know how to implement the multiple upload or better said, how to upload all files at all.
There are some tutorials in the internet, that you can simply find by googling "multiple file upload". Anyway here is one of the examples:
The HTML
<!-- IMPORTANT: FORM's enctype must be "multipart/form-data" -->
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
</form>
Listing Multiple Files with JavaScript
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
//empty list for now...
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
//for every file...
for (var x = 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
The input.files property provides an array of files for which you can check the length; if there's a length, you can loop through each file and access the file paths and names.
Receiving and Handling Files with PHP
if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
PHP creates an array of the files uploaded with the given INPUT's name. This variable will always be an array within PHP.
Source
Demo
This is uploading using ajax. There are other ways such the use of iframe and jquery's $.load().
ajax_upload.js
Hmm... FormData is not IE-safe. So, you may want to resort to iframe & $.load().
function doUpload(fle_id, url_upld)
{
var upldLimit = 2000000; // 2mb by default;
if( $('#'+fle_id)[0] == undefined || $('#'+fle_id)[0].files.length == 0 ) {
alert('nothing to upload');
return;
}
// put files to formData
var tfSize = 0; // in bytes
var fd = new FormData();
$.each($('#'+fle_id)[0].files, function(i, file) {
fd.append(i, file);
tfSize = tfSize + file.size;
});
// you may check file size before sending data
if(tfSize > upldLimit) {
alert('File upload exceeded the '+(upldLimit/1000000)+' MB limit.');
return;
}
// actual data transfer
$.ajax({
url: url_upld,
cache: false,
data: fd,
type: 'POST',
contentType : false,
processData : false,
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
}
upload_form.html
Let's use jquery to make things simple.
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="ajax_upload.js"></script>
<script type="text/javascript">
$(function(){
$('form').submit(function(e){
if( e.preventDefault ) e.preventDefault(); // chrome/firefox
else e.cancelBubble(); // IE
// supply file input id and upload url
doUpload( 'fle', $(this).attr('action') );
});
});
</script>
Upload
<form action="ajax_upload.php"
method="post"
enctype="multipart/form-data"
accept-charset="utf-8"
>
<input type="file" id="fle" name="fle[]" multiple >
<button type="submit">Upload</button>
</form>
ajax_upload.php
<?php
if(count($_FILES) == 0) {
echo 'Nothing uploaded.';
exit;
}
$upldPath = 'E:/stack/upload/';
foreach($_FILES as $file) {
if ($file['error'] == UPLOAD_ERR_OK) {
try {
if( !move_uploaded_file( $file["tmp_name"], $upldPath . $file['name']) ) {
// abort even if one file cannot be moved.
echo 'Cannot upload one of the files.';
exit;
}
}
catch(Exception $e) {
echo 'Cannot upload the files.';
exit;
}
} else {
// abort even if one file has error.
echo 'Cannot upload one of the files.';
exit;
}
}
echo 'Upload successful!';
?>
Here is a simple approach to solving this issue.
This FormData append method works on IE 10 up and any other browser.
let files = []
let formData = new FormData
let filesInput = document.getElementById('files')
function prepareFiles() {
files = filesInput.files
}
function uploadFiles() {
// Arrange the files as form data to be sent to php
files = Array.from(files)
files.forEach(file => formData.append('files[]', file))
// See all selected files
console.log('Files')
console.log(formData.getAll('files[]'))
// Then send to php with jquery, axios e.t.c
console.log('Server response')
$.post('/pathtophpscript', formData, (response) => {
console.log(response)
}).catch(error => console.log(error))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" name="uploads" id="files" onchange="prepareFiles()" multiple>
<br/><br/>
<input type="submit" name="Upload" onclick="uploadFiles()">
Related
I've searched everything but my error stays.
Following scripts is my code:
var client = null;
function fileChange()
{
var fileList = document.getElementById("fileA").files;
var file = fileList[0];
if(!file)
return;
document.getElementById("progress").value = 0;
document.getElementById("prozent").innerHTML = "0%";
}
function uploadFile()
{
var file = document.getElementById("fileA").files[0];
var formData = new FormData();
client = new XMLHttpRequest();
var prog = document.getElementById("progress");
if(!file)
return;
prog.value = 0;
prog.max = 100;
formData.append("datei", file);
client.onerror = function(e) {
alert("onError");
};
client.onload = function(e) {
document.getElementById("prozent").innerHTML = "100%";
prog.value = prog.max;
};
client.upload.onprogress = function(e) {
var p = Math.round(100 / e.total * e.loaded);
document.getElementById("progress").value = p;
document.getElementById("prozent").innerHTML = p + "%";
};
client.onabort = function(e) {
alert("Upload abgebrochen");
};
client.open("POST", "upload.php");
client.send(formData);
}
And my upload.php:
<?php
if (isset($_FILES['datei']))
{
//console.log("upload.php!");
//move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/'.basename($_FILES['datei']['name']));
move_uploaded_file($_FILES['datei']['tmp_name'], 'upload/hextoflash.hex');
}
else
{
echo "error in $_files";
}
?>
and html:
<form name="uploadform" method="post" enctype="multipart/form-data" action="">
<br> <input name="uploaddatei" type="file" id="fileA" onchange="fileChange();" /> </br>
<input name="uploadbutton" value="Hochladen!" style="width: 108px" type="button" onclick="uploadFile();" />
</form>
The point is, i already tried to edit php.ini.
I checked max_size and so on, its already in the right dimension
File was working with an old jquery.js, i updated to jquery2.2.0 because of datatables plugin, so i need that, and since then it seems to not work anymore
the rights of the upload folder are 777
So i don't get where the problem is, and if its within jquery, im not able to fix that. is there a method to fix this problem?
I found the solution.
It was so easy i would never think of it.
The server drive was simply 100% full.
Deleted some junk and voilá it's running.
Iam writing a script that uploads files via Drag and Drop using jQuery which reads the file on drop and adds it to an array of files like so:
var files = [];
$(document).ready(function() {
jQuery.fn.dropbox = function(config) {
var dragging = 0;
var dragEnter = function(e) {
e.stopPropagation();
e.preventDefault();
dragging++;
$(".external-drop-indicator").fadeIn();
$(".toast.toast-success").fadeIn().css("display", "inline-block");;
return false;
};
var dragOver = function(e) {
e.stopPropagation();
e.preventDefault();
return false;
};
var dragLeave = function(e) {
e.stopPropagation();
e.preventDefault();
dragging--;
if(dragging === 0) {
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
}
return false;
};
var drop = function(e) {
var dt = e.dataTransfer;
var files_upload = dt.files;
e.stopPropagation();
e.preventDefault();
if(files_upload && files_upload.length > 0 && config.onDrop !== undefined) {
files.push(files_upload);
config.onDrop(files_upload);
}
$(".external-drop-indicator").fadeOut();
$(".toast.toast-success").fadeOut();
};
var applyDropbox = function(dropbox) {
dropbox.addEventListener('dragenter', dragEnter, false);
dropbox.addEventListener('dragover', dragOver, false);
dropbox.addEventListener('dragleave', dragLeave, false);
dropbox.addEventListener('drop', drop, false);
};
return this.each(function() {
applyDropbox(this);
});
};
});
In summary what it does is, adds an extended jQuery function to enable drag and drop on a certain element of the website in which the function is applied.
Then I apply the extended functionality to the body for it to enable the file Drag and Drop functionality like so:
$(document).ready(function() {
$('body').dropbox({
onDrop: function(f) {
$(f).each(function(idx, data) {
var file_name = data.name;
var extension = file_name.split('.');
file_name = extension[0];
extension = extension[1];
if(extension == 'pdf' || extension == 'xls') {
showAjaxModal(base_url + 'index.php?modal/popup/file_create/' + folder_id + '/' + extension + '/' + file_name);
} else {
$(".upload-area").append('<div class="alert alert-danger" style="display:inline-block;width:480px;"><strong>Error!</strong> File type is incorrect.</div>');
}
});
}
});
});
In summary what this does is adds the Drag and Drop functionality to the body and when a file is dropped it detects the extension of the file by splitting the name and the extension, so that I can verify that the extension of the file that was dropped is correct. Then it proceeds to show a modal to fill information about the file that is being uploaded for later submission, if the file extension is correct.
Then I proceed to fill the file information using CodeIgniter's function "form_open()" when the modal pops like so:
<?php echo form_open(base_url() . 'index.php?client/file/create/' . $param2, array('class' => 'form-horizontal form-groups-bordered validate ajax-upload', 'enctype' => 'multipart/form-data')); ?>
<div class="col-md-4 file-info">
<div class="icon-<?=($param3 == 'pdf' ? 'pdf' : 'document')?>"></div>
<p>
<?php echo $param4;?>
</p>
</div>
<div class="col-md-8 new-file">
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="tags" data-validate="required" data-message-required="Field is required" placeholder="File tags" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<input type="text" class="form-control" name="name" data-validate="required" data-message-required="Field is required" placeholder="File name" value="" autofocus>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-12">
<div class="input-group">
<textarea rows="5" class="form-control" name="description" data-validate="required" data-message-required="Field is required" placeholder="File description" value="" autofocus></textarea>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-7">
<button type="submit" class="btn btn-info" id="submit-button">Upload</button>
<span id="preloader-form"></span>
</div>
</div>
<?php echo form_close(); ?>
This basically creates a form which later will be submitted via Ajax.
Now I proceed to handle the file submission via jQuery for the information to be sent with the file or files that are being uploaded like so:
$(document).ready(function(e) {
$('.ajax-upload').submit(function(e) {
e.preventDefault();
var $elm = $(this);
var fd = new FormData();
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
var form_data = $(".ajax-upload").serializeArray();
$.each(form_data, function(key, input) {
fd.append(input.name, input.value);
});
var opts = {
url: $elm.attr('action'),
data: fd,
cache: false,
contentType: false,
processData: false,
type: 'POST',
beforeSend: uValidate,
success: showResponse
};
if(fd.fake) {
opts.xhr = function() {
var xhr = jQuery.ajaxSettings.xhr();
xhr.send = xhr.sendAsBinary;
return xhr;
}
opts.contentType = "multipart/form-data; boundary=" + fd.boundary;
opts.data = fd.toString();
}
jQuery.ajax(opts);
return false;
});
});
Basically the form default action is overwritten and the files that were submitted on the previous code chunk for the drag and drop functionality are now appended to formData which later gets joined by the form data that was on the form I submit. Then the formData is sent via an AJAX call.
Now the controller looks like this, it handles the AJAX call and then executes the File Upload method on the model like so:
function file($param1 = '', $param2 = '', $param3 = 0) {
if ($this->session->userdata('client_login') != 1) {
$this->session->set_userdata('last_page', current_url());
redirect(base_url(), 'refresh');
}
if ($param1 == 'create')
$this->crud_model->create_file($param2);
if ($param1 == 'edit')
$this->crud_model->update_file($param2);
if ($param1 == 'delete')
$this->crud_model->delete_file($param2, $param3);
$page_data['page_name'] = 'files';
$page_data['page_title'] = 'Files List';
$page_data['folder_id'] = $param3;
$this->load->view('backend/index', $page_data);
}
Here is the model method:
function create_file($folder_id) {
$data['name'] = $this->input->post('name');
$data['tags'] = $this->input->post('tags');
$data['description'] = $this->input->post('description');
$data['type'] = 'file';
$data['folder_id'] = $folder_id;
$data['client_id'] = $this->session->userdata('login_user_id');
$config['upload_path'] = 'uploads/tmp/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$this->load->library('upload');
$this->upload->initialize($config);
var_dump($_FILES);
die();
foreach($_FILES as $field => $file)
{
//var_dump($_FILES); die();
// No problems with the file
if($file['error'] == 0)
{
// So lets upload
if ($this->upload->do_upload($field))
{
$data = $this->upload->data();
echo $data['full_path'];
}
else
{
$errors = $this->upload->display_errors();
var_dump($errors);
}
}
}
$this->db->insert('client_files' , $data);
}
So basically what happens is that the $_FILES array is empty, and the file doesn't get uploaded.
The "Request Payload" as viewed on Chrome's Developer Tools looks like this:
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="file_0"
[object FileList]
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="tags"
bsd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="name"
asd
------WebKitFormBoundaryvVAxgIQd6qU8BtkF
Content-Disposition: form-data; name="description"
asd
And the response I get from the var_dump() on the model is the following:
array(0) {
}
I have tried the solution on this question: Sending multipart/formdata with jQuery.ajax But no luck so far.
Any idea on what am I doing wrong and how to fix this issue? Thanks.
The problem here is that I'm sending the array of files instead of the single files on the AJAX call, specifically in this part of the code:
for(var i = 0; i < files.length; i++) {
fd.append("file_" + i, files[i]);
}
The solution was to append file by file to the formData instead of the array of files, something like this:
for(var i = 0; i < files[0].length; i++) {
fd.append("file_" + i, files[i]);
}
This will append every single file of the files array instead of the array of files itself and it solves the problem.
In conclusion I was sending the array of files instead of the single files, the clue to this was the [object FileList] that the request was showing instead of the files information, which now makes a request like this:
Content-Disposition: form-data; name="file"; filename="exfile.pdf"
Content-Type: application/pdf
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.
I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});
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;
}
});