I'm making an upload function with php, which works fine.
Only, because the maximum size in my php ini file is 32mb, I can't upload anything bigger than that. And that's fine with me.
BUT:
I want to prevent uploading when the combined size of all the files that are added to input-file, is over 32mb.
I found this script which alerts the file size after adding the files, which is a start:
$(function(){
$('#file').change(function(){
var file=this.files[0]
alert(file.size||file.fileSize)
})
})
But when testing I found out that it only returns the size of one file.
How can I alter this code to return the size of all the files that are added to the input field? Or is there another way to do this?
HTML:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Tutorial</title>
<link rel="stylesheet" type="text/css" href="css/tut.css">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<form action="tutorial.php" method="POST" enctype="multipart/form-data">
<!--<input type="file" name="myFile"><p>
<input type="submit" value="Upload">
<br/><br/>-->
<input type="file" name="files[]" multiple="multiple" id="file"/><p>
<input type="submit" value="Upload" id="submit" />
</form>
</div>
</body>
</html>
PHP code:
$file_dest = "photos/orig/";
$thumb_dest = "photos/thumbs/";
if(!empty($_FILES['files']['name'][0])){
$files = $_FILES['files'];
$uploaded = array();
$failed = array();
$allowedExt = array('png', 'jpg', 'gif');
foreach($files['name'] as $position => $file_name) {
$file_tmp = $files['tmp_name'][$position];
$file_size = $files['size'][$position];
$file_error = $files['error'][$position];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
if(in_array($file_ext, $allowedExt)){
if($file_error == 0){
if($file_size <= 20000000){
$file_name_new = uniqid('', true)."_".$file_name;
$file_move = $file_dest.$file_name_new;
if(move_uploaded_file($file_tmp, $file_move)){
$uploaded[$position] = $file_dest;
}else{
$failed[$position] = "[{$file_name}] failed to upload.";
}
}else{
$failed[$position] = "[{$file_name}] is too large.";
}
}else{
$failed[$position] = "[P$file_name}] errored with code {$file_error}";
}
}else{
$failed[$position] = "[{$file_name}] file extension '{$file_ext}' is not allowed.";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}else{
echo "No files were added.";
}
Sidenote: The code's not finished yet, I still have to add security measures. Please ignore the lack thereof.
You'd do that by summing up the sizes
$(function(){
$('#file').on('change', function(){
var total = [].slice.call(this.files).map(function(x) {
return x.size || x.fileSize;
}).reduce(function(a, b) { return a + b; }, 0);
if ( total > 33554432 ) {
alert('Total size exceeds 32 mb');
}
});
});
FIDDLE
$(function(){
$('#file').change(function(){
var combinedSize = 0;
for(var i=0;i<this.files.length;i++) {
combinedSize += (this.files[i].size||this.files[i].fileSize);
}
alert(combinedSize);
})
})
Related
Aim:
The background loop will continuously read and print the file (word.txt)
Pressing one of the buttons will overwrite the value in word.txt
This change will then be read by the background loop and printed
What happens:
The background loop continuously reads and prints the file (word.txt)
Pressing one of the buttons overwrites the value in word.txt
but.... 3. This change isn't reflected in JS until I go on to the "word.txt" file in a different browser and refresh the page. Once this is done, JS starts recognizing it.
Any ideas? Sorry the snippet doesn't work as it has php in
var instanse = false;
var state;
var mes;
var file;
console.log('update.js loaded');
function triggerUpdate(){
console.log('update.js is triggered');
updateChat();
}
//Background Loop
function updateChat(){
var file = 'word.txt';
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
setTimeout(updateChat, 1500);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Random Word Generator</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript"></script>
<script language="javascript" src="update.js" type="text/javascript"></script>
</head>
<body onload="triggerUpdate();">
<form action="" method="post">
<input type="submit" name="word"
class="button" value="Button1" id="button1"/>
<input type="submit" name="word"
class="button" value="Button2" id="button2"/>
</form>
<?php
//This function gets called when button is pushed
function postword(){
$fp = fopen('word.txt', 'w');
fwrite($fp, $_POST['word']);
fclose($fp);
}
//When the button is pushed, the function will be called
if (isset($_POST['word'])) {
postword();
return;
}
?>
</body>
</html>
The browser is caching the initial result of the XMLHttpRequest call. The easiest workaround is to fool the cache by appending a random number as a parameter to the url. it will get ignored by the filesystem when looking for the file.
You can add any query variable you want ('v' is popular - sort of stands for version).
There are many ways to get a random number but using the Unix timestamp - Date.now()
- is an easy one that should do the trick in this case.
Change code from:
var file = 'word.txt';
To:
var file = 'word.txt?v=' + Date.now();
This which will create a call to a url like this: word.txt?v=1519211809934
I want to save data in the input when the page reloading and I don't
know why my code doesn't work. This is my html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<label>nom:</label> <input type="text" value=""/></br>
<label>prenom:</label><input type="text" value=""/>
<script type="text/javascript">
window.onbeforeunload = function(){
localStorage.setItem(nom, document.getElementsByTagName('input')[0].value);
localStorage.setItem(prenom, document.getElementsByTagName('input')[1].value);
}
document.addEventListener("DOMContentLoaded",function(){
var nom = localStorage.getItem(nom);
var prnom = localStorage.getItem(prenom);
if(nom!==null&&prenom!==null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
});
</script>
</body>
</html>
Make sure to use quotes for the variable name:
localStorage.setItem('nom', document.getElementsByTagName('input')[0].value);
Or you can use this which is simpler:
localStorage.nom = document.getElementsByTagName('input')[0].value;
Your code was setting the localStorage values when the page was loaded which means it set it to be no text so the code won't save.
Use the below code:
window.onbeforeunload = function() {
var nom = localStorage.nom;
var prnom = localStorage.prenom;
if (nom !== null && prenom !== null) {
document.getElementsByTagName('input')[0].value = nom;
document.getElementsByTagName('input')[1].value = prenom;
}
};
<label>nom:</label> <input type="text" onchange="localStorage.nom = document.getElementsByTagName('input')[0].value" /></br>
<label>prenom:</label><input type="text" onchange=" localStorage.prenom = document.getElementsByTagName('input')[1].value" />
IMPORTANT: use the code on your computer because localStorage doesn't work on stack overflow snippets
I have been trying to read data from file ans display it into some kind of listBov in html page by using java script.
I have been trying many cources, but there is no working code (I've trying on IE, Firefox and Chrome)
There is one of the attempt to do that, but it also without success:
File 1:
indexTST.html
<html>
<head>
<script language="JavaScript" type="text/javascript" src="java.js">
</script>
<body>
<td><form name="listBox" action="javascript:void 0;">
<select name="listBox" size="10">
<option>Select your home location</option>
<option>unknown</option>
</select>
</form>
<script type="text/javascript" language="JavaScript">
loadData();
with (document.listBox) {
listBox.options.length=0;
for (var i=0; i<Table.length; i++) {
listBox.options[listBox.options.length]=new Option(Table[i]);
}
}
reset1();
</script>
</body>
</html>
File 2:
java.js
var Table = [];
var txtFile;
function loadData2() {
Table = [];
lines = txtFile.responseText.split("\n");
for (i = 0; i < lines.length-1; i++) {
Table.push(lines[i]);
}
}
function loadData() {
var f = "dataFile.txt";
alert('01');
txtFile.open("GET", f, false);
alert('02');
txtFile.onreadystatechange=loadData2;
txtFile.send(null);
}
File 4:
dataFile.txt
Data 01
Data 02
Data 03
end
What I'm trying to achieve is:
Read text data from file (between 1 and 5 000 lines) and the file is on the server side (not local browser side)
Display it into some kind of listBox on web page
It's need to be "clickable/selectable" - because when user select i.e. item 5 - this one item need to be save into "saved.txt"
Thanks for help
Read a file and appends its contents by line to a list, and log the selected options. I hope it helps.
<!DOCTYPE html>
<html>
<body>
<h3>Read file</h3>
<input id="file-input" type="file" id="myFile">
<select multiple id="list"></select>
<button onclick="logSelected()">Log selected</button>
<script>
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
console.log(contents);
var select = document.getElementById('list');
var lines = contents.split('\n');
lines.map(function(line){
var docLine = document.createElement('option');
docLine.innerHTML = line;
select.appendChild(docLine);
});
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('file-input').addEventListener('change', readSingleFile, false);
function logSelected(){
var select = document.getElementById("list");
var selected = [];
for (var i = 0; i < select.length; i++) {
if (select.options[i].selected) selected.push(select.options[i].value);
}
console.log(selected);
};
</script>
</body>
</html>
I'm trying to get the size of a file from a file-input control.
To do this I'm using jquery:
function init() {
$("#cphInhalt_cphInhalt_file0").bind("change", function() {
handleFileSelect(this);
});
}
function handleFileSelect(e) {
if (e.files[0].size + totalFileSize > 3000000) {
addNewUpload(e);
$(e).remove();
if (getCookie("language") == "German") {
alert("Die gesamte Dateigröße wurde überschritten");
} else {
alert("The total file size has been exceeded");
}
return;
}
In any browser this works fine, except of Internet explorer ( using version 11) , but as I think it should support the File Api right?
It says e.files is undefinied
It will ask for Enable ActiveX in your browser, please say allow
<!DOCTYPE html>
<html>
<head>
<script language="javascript" type="text/javascript">
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size +" bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onclick="getSize();">
</form>
</body>
</html>
This ans was given in how validate file size using HTML and Javascript on client side
The problem was, that the IE set himself into a Version 7 compatibility mode.
I am looking for some sort of image uploader and cropper that works mainly client side before it saves to the server.
I have tried a few things but have the issue that most of it is html5 based and I can't seem to find some sort of flash based uploader for the older browsers.
I got slightly lost with the jquery file uploader which I know can be used in the older browsers and the still need to work on a cropping function (but that looks like it will be mostly server side which would be a last resort).
I have also used http://www.script-tutorials.com/html5-image-uploader-with-jcrop/ which sort of works it uploads but when I want to test the crop function it keeps opening up the upload.php file. I will put the code below here :
<!DOCTYPE html >
<html>
<head>
<title>test image uploader</title>
<!--Stylesheets-->
<link href="css/colorbox.css" rel="stylesheet"/>
<link href="css/jquery.Jcrop.min.css" rel="stylesheet"/>
<!-- scripts-->
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.Jcrop.min.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
</head>
<body >
<form id="upload_form" enctype="multipart/form-data" method="post" action="upload.php" onsubmit="return checkForm();">
<input type="hidden" id="x1" name="x1" />
<input type="hidden" id="y1" name="y1" />
<input type="hidden" id="x2" name="x2" />
<input type="hidden" id="y2" name="y2" />
<h2>Please select image file</h2>
<div>
<input type="file" name="image_file" id="image_file" onchange="fileSelectHandler();"/>
</div>
<div class="error"></div>
<div class="step2">
<h2>Please select a crop region</h2>
<img id="preview" />
<div class="info">
<label>File size</label><input type="text" id="filesize" name="filesize" />
<label>Type</label><input type="text" id="filetype" name="filetype" />
<label>Image dimension</label><input type="text" id="filedim" name="filedim" />
<label>W</label><input type="text" id="w" name="w" />
<label>H</label><input type="text" id="h" name="h" />
</div>
<input type="submit" value="Upload" />
</div>
</form>
</body>
<script type="text/javascript">
// convert bytes into friendly format
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB'];
if (bytes == 0) return 'n/a';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
};
// check for selected crop region
function checkForm() {
if (parseInt($('#w').val())) return true;
$('.error').html('Please select a crop region and then press Upload').show();
return false;
};
// update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
$('#x1').val(e.x);
$('#y1').val(e.y);
$('#x2').val(e.x2);
$('#y2').val(e.y2);
$('#w').val(e.w);
$('#h').val(e.h);
};
// clear info by cropping (onRelease event handler)
function clearInfo() {
$('.info #w').val('');
$('.info #h').val('');
};
function fileSelectHandler() {
// get selected file
var oFile = $('#image_file')[0].files[0];
// hide all errors
$('.error').hide();
// check for image type (jpg and png are allowed)
var rFilter = /^(image\/jpeg|image\/png)$/i;
if (!rFilter.test(oFile.type)) {
$('.error').html('Please select a valid image file (jpg and png are allowed)').show();
return;
}
// check for file size
if (oFile.size > 250 * 1024) {
$('.error').html('You have selected too big file, please select a one smaller image file').show();
return;
}
// preview element
var oImage = document.getElementById('preview');
// prepare HTML5 FileReader
var oReader = new FileReader();
oReader.onload = function (e) {
// e.target.result contains the DataURL which we can use as a source of the image
oImage.src = e.target.result;
oImage.onload = function () { // onload event handler
// display step 2
$('.step2').fadeIn(500);
// display some basic image info
var sResultFileSize = bytesToSize(oFile.size);
$('#filesize').val(sResultFileSize);
$('#filetype').val(oFile.type);
$('#filedim').val(oImage.naturalWidth + ' x ' + oImage.naturalHeight);
// Create variables (in this scope) to hold the Jcrop API and image size
var jcrop_api, boundx, boundy;
// destroy Jcrop if it is existed
if (typeof jcrop_api != 'undefined')
jcrop_api.destroy();
// initialize Jcrop
$('#preview').Jcrop({
minSize: [100, 100], // min crop size
boxWidth:600,
aspectRatio: 9/6, // keep aspect ratio 1:1
bgFade: true, // use fade effect
bgOpacity: .4, // fade opacity
onChange: updateInfo,
onSelect: updateInfo,
onRelease: clearInfo
}, function () {
// use the Jcrop API to get the real image size
var bounds = this.getBounds();
boundx = bounds[0];
boundy = bounds[1];
// Store the Jcrop API in the jcrop_api variable
jcrop_api = this;
});
};
};
// read selected file as DataURL
oReader.readAsDataURL(oFile);
}
</script>
</html>
here is the upload.php code :
<?php
/**
*
* HTML5 Image uploader with Jcrop
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2012, Script Tutorials
* http://www.script-tutorials.com/
*/
function uploadImageFile() { // Note: GD library is required for this function
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$iWidth = $iHeight = 200; // desired image result dimensions
$iJpgQuality = 90;
if ($_FILES) {
// if no errors and size less than 250kb
if (! $_FILES['image_file']['error'] && $_FILES['image_file']['size'] < 250 * 1024) {
if (is_uploaded_file($_FILES['image_file']['tmp_name'])) {
// new unique filename
$sTempFileName = 'cache/' . md5(time().rand());
// move uploaded file into cache folder
move_uploaded_file($_FILES['image_file']['tmp_name'], $sTempFileName);
// change file permission to 644
#chmod($sTempFileName, 0644);
if (file_exists($sTempFileName) && filesize($sTempFileName) > 0) {
$aSize = getimagesize($sTempFileName); // try to obtain image info
if (!$aSize) {
#unlink($sTempFileName);
return;
}
// check for image type
switch($aSize[2]) {
case IMAGETYPE_JPEG:
$sExt = '.jpg';
// create a new image from file
$vImg = #imagecreatefromjpeg($sTempFileName);
break;
/*case IMAGETYPE_GIF:
$sExt = '.gif';
// create a new image from file
$vImg = #imagecreatefromgif($sTempFileName);
break;*/
case IMAGETYPE_PNG:
$sExt = '.png';
// create a new image from file
$vImg = #imagecreatefrompng($sTempFileName);
break;
default:
#unlink($sTempFileName);
return;
}
// create a new true color image
$vDstImg = #imagecreatetruecolor( $iWidth, $iHeight );
// copy and resize part of an image with resampling
imagecopyresampled($vDstImg, $vImg, 0, 0, (int)$_POST['x1'], (int)$_POST['y1'], $iWidth, $iHeight, (int)$_POST['w'], (int)$_POST['h']);
// define a result image filename
$sResultFileName = $sTempFileName . $sExt;
// output image to file
imagejpeg($vDstImg, $sResultFileName, $iJpgQuality);
#unlink($sTempFileName);
return $sResultFileName;
}
}
}
}
}
}
$sImage = uploadImageFile();
echo '<img src="'.$sImage.'" />';
The other problem with it is I have no fall back option for the older browsers mainly IE8 and 9 because of it only being html5 based.
can anyone please help with any idea's please.