So I've been working on a HTML form for graphical upload and it turned out to be more confusing that i originally thought. The code i have written works on Chromium 62.0.3202.94, however on Firefox 57.0 the percentage stays at 0% and won't change. Does anyone have any idea why this might be happening? here's the code:
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>File upload with progress</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById("fileToUpload").files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById("fileName").innerHTML = "Name: " + file.name;
document.getElementById("fileSize").innerHTML = "Size: " + fileSize;
document.getElementById("fileType").innerHTML = "Type: " + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", "upload.php");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById("percent").innerHTML = percentComplete.toString() + "%";
}
else {
document.getElementById("percent").innerHTML = "unable to compute";
}
}
</script>
</head>
<body>
<h1>File upload with progress bar</h1>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="myFile" id="fileToUpload" onchange="fileSelected();">
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="submit" onclick="uploadFile()" value="Upload">
</div>
<div class="progress">
<div class="bar"></div>
<div class="percent" id="percent">0%</div>
</div>
</form>
</body>
</html>
There is one big issue with the code - browsers default submit action is not prevented.
Prevented by:
Removing un-needed attributes from <form>
Removing the onclick handler from the <submit>. Using <form onsubmit instead.
<form onsubmit handler (uploadFile) returns false.
After cleaning that up in the code, after that worked in Chrome 62.0.3202.94 and Firefox 57.0, IE 11.
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<title>File upload with progress</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById("fileToUpload").files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById("fileName").innerHTML = "Name: " + file.name;
document.getElementById("fileSize").innerHTML = "Size: " + fileSize;
document.getElementById("fileType").innerHTML = "Type: " + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.open("POST", "upload.php");
xhr.send(fd);
return false; // Prevent browser default submit action
}
function uploadProgress(evt) {
console.log("uploadProgress", evt);
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById("percent").innerHTML = percentComplete.toString() + "%";
}
else {
document.getElementById("percent").innerHTML = "unable to compute";
}
}
</script>
</head>
<body>
<h1>File upload with progress bar</h1>
<form onsubmit="return uploadFile()">
<div class="row">
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="myFile" id="fileToUpload" onchange="fileSelected();">
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="submit" value="Upload">
</div>
<div class="progress">
<div class="bar"></div>
<div class="percent" id="percent">0%</div>
</div>
</form>
</body>
</html>
Related
I have the code for the image preview but after removing it only goes from preview but not from url variable and the removed images url are also being stored in database.
I'm using Spring Boot for controllers.
how to remove the image while clicking the remove button and also uploaded link from the uploaded files list
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\"title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
</script>
<style>
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
</style>
</head>
<body>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" multiple="multiple" />
</div>
</body>
</html>
Please help how to remove the image from preview and also from pojo variable that being saved to database.
Do empty input file field as well
$(".remove").click(function(){
$(this).parent(".pip").remove();
$("#files").val(null);
});`
This is the used for upload,crop,cut then display image,
but I want to display cropped image and (x1,y1,), (x2,y2) coordinates of cropped image.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<link rel="stylesheet" href="css/style.css" />
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="
https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css
">
<style>
.page {
margin: 1em auto;
max-width: 768px;
display: flex;
align-items: flex-start;
flex-wrap: wrap;
height: 100%;
}
.box {
padding: 0.5em;
width: 100%;
margin:0.5em;
}
.box-2 {
padding: 0.5em;
width: calc(100%/2 - 1em);
}
.options label,
.options input{
width:4em;
padding:0.5em 1em;
}
.btn{
background:white;
color:black;
border:1px solid black;
padding: 0.5em 1em;
text-decoration:none;
margin:0.8em 0.3em;
display:inline-block;
cursor:pointer;
}
.hide {
display: none;
}
img {
max-width: 100%;
}
</style>
</head>
<body>
<div class="container">
<h1>Cropper with a range of aspect ratio</h1>
<div>
<main class="page">
<h2>Upload ,Crop and save.</h2>
<!-- input file -->
<div class="box">
<input type="file" id="file-input">
</div>
<!-- leftbox -->
<div class="box-2">
<div class="result" id="image"></div>
</div>
<!--rightbox-->
<div class="box-2 img-result hide">
<form><img alt="" class="cropped" src=""></form>
</div>
<!-- input file -->
<div class="box">
<div class="options hide">
<label> Width</label>
<input type="number" class="img-w" value="300" min="100" max="1200" />
</div>
<!-- save btn -->
<button class="btn save hide" >Save</button>
<!-- download btn -->
</div>
</main>
</div>
</div><br><br><br><br><br>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js
"></script>
<script>
// vars
let result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
dwn = document.querySelector('.download'),
upload = document.querySelector('#file-input'),
cropper = '';
// on change show image with crop options
upload.addEventListener('change', (e) => {
if (e.target.files.length) {
// start file reader
const reader = new FileReader();
reader.onload = (e)=> {
if(e.target.result){
// create new image
let img = document.createElement('img');
img.id = 'image';
img.src = e.target.result
// clean result before
result.innerHTML = '';
// append new image
result.appendChild(img);
// show save btn and options
save.classList.remove('hide');
options.classList.remove('hide');
// init cropper
cropper = new Cropper(img);
// cropped value
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener('click',(e)=>{
e.preventDefault();
// get result to data uri
let imgSrc = cropper.getCroppedCanvas({
width: img_w.value // input value
}).toDataURL();
// remove hide class of img
cropped.classList.remove('hide');
img_result.classList.remove('hide');
// show image cropped
cropped.src = imgSrc;
dwn.classList.remove('hide');
dwn.download = 'imagename.png';
dwn.setAttribute('value',imgSrc);
});
</script>
</body>
</html>
Please can anyone help me? How do I find (x1,y1,), (x2,y2) coordinates of cropped image? I have some idea about that: First find (x1,y1,) and width and height of cropped image then x2=x1+width , y2=y1+width, but I don't know how to apply. Please help me with how apply this to Javascript or jQuery.
Working example with both: absolute canvas coordinates and relative image coordinates:
// vars
let result = document.querySelector('.result'),
img_result = document.querySelector('.img-result'),
img_w = document.querySelector('.img-w'),
img_h = document.querySelector('.img-h'),
options = document.querySelector('.options'),
save = document.querySelector('.save'),
cropped = document.querySelector('.cropped'),
dwn = document.querySelector('.download'),
upload = document.querySelector('#file-input'),
cropper = '';
// on change show image with crop options
upload.addEventListener('change', (e) => {
if (e.target.files.length) {
// start file reader
const reader = new FileReader();
reader.onload = (e) => {
if (e.target.result) {
// create new image
let img = document.createElement('img');
img.id = 'image';
img.src = e.target.result
// clean result before
result.innerHTML = '';
// append new image
result.appendChild(img);
// show save btn and options
save.classList.remove('hide');
options.classList.remove('hide');
// init cropper
cropper = new Cropper(img);
// cropped value
}
};
reader.readAsDataURL(e.target.files[0]);
}
});
// save on click
save.addEventListener('click', (e) => {
let cropLeft = cropper.cropBoxData.left;
let cropTop = cropper.cropBoxData.top;
let cropRight = cropLeft + cropper.cropBoxData.width;
let cropBottom = cropTop + cropper.cropBoxData.height;
let info = "Crop region (absolute canvas coordinates):\n" +
"(x1, y1) = (" + cropLeft + ", " + cropTop + ")\n" +
"(x2, y2) = (" + cropRight + ", " + cropBottom + ")\n";
let zoom = cropper.image.offsetHeight / cropper.image.naturalHeight;
let naturalWidth = (cropRight - cropLeft) / zoom;
let naturalHeight = (cropBottom - cropTop) / zoom;
let relativeLeft = (cropper.cropBoxData.left - cropper.canvasData.left);
let relativeTop = (cropper.cropBoxData.top - cropper.canvasData.top);
let naturalLeft = relativeLeft / zoom;
let naturalTop = relativeTop / zoom;
let naturalRight = naturalLeft + naturalWidth;
let naturalBottom = naturalTop + naturalHeight;
info += "\nCrop region (image coordinates):\n" +
"(x1, y1) = (" + naturalLeft + ", " + naturalTop + ")\n" +
"(x2, y2) = (" + naturalRight + ", " + naturalBottom + ")\n";
alert(info);
e.preventDefault();
// get result to data uri
let croppedImg = cropper.getCroppedCanvas({
width: img_w.value // input value
});
let imgSrc = croppedImg.toDataURL();
// remove hide class of img
cropped.classList.remove('hide');
img_result.classList.remove('hide');
// show image cropped
cropped.src = imgSrc;
});
.page {
margin: 1em auto;
max-width: 768px;
display: flex;
align-items: flex-start;
flex-wrap: wrap;
height: 100%;
}
.box {
padding: 0.5em;
width: 100%;
margin: 0.5em;
}
.box-2 {
padding: 0.5em;
width: calc(100%/2 - 1em);
}
.options label,
.options input {
width: 4em;
padding: 0.5em 1em;
}
.btn {
background: white;
color: black;
border: 1px solid black;
padding: 0.5em 1em;
text-decoration: none;
margin: 0.8em 0.3em;
display: inline-block;
cursor: pointer;
}
.hide {
display: none;
}
img {
max-width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Cropper.js</title>
<link href='https://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="
https://cdnjs.cloudflare.com/ajax/libs/cropper/2.3.4/cropper.min.css
">
</head>
<body>
<div class="container">
<h1>Cropper with a range of aspect ratio</h1>
<div>
<main class="page">
<h2>Upload ,Crop and save.</h2>
<!-- input file -->
<div class="box">
<input type="file" id="file-input">
</div>
<!-- leftbox -->
<div class="box-2">
<div class="result" id="image"></div>
</div>
<!--rightbox-->
<div class="box-2 img-result hide">
<form><img alt="" class="cropped" src=""></form>
</div>
<!-- input file -->
<div class="box">
<div class="options hide">
<label> Width</label>
<input type="number" class="img-w" value="300" min="100" max="1200" />
</div>
<!-- save btn -->
<button class="btn save hide">Save</button>
<!-- download btn -->
</div>
</main>
</div>
</div><br><br><br><br><br>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/0.8.1/cropper.min.js
"></script>
</body>
</html>
I have code below that runs perfectly and uploads multiple images.
This is the html and jQuery code:
<div class="field" align="left">
<span>
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</span>
</div>
The script is as below:
<style>
input[type="file"] {
display:block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
margin: 10px 10px 0 0;
padding: 1px;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
if(window.File && window.FileList && window.FileReader) {
$("#files").on("change",function(e) {
var files = e.target.files ,
filesLength = files.length ;
for (var i = 0; i < filesLength ; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<img></img>",{
class : "imageThumb",
src : e.target.result,
title : file.name
}).insertAfter("#files");
});
fileReader.readAsDataURL(f);
}
});
} else { alert("Your browser doesn't support to File API") }
});
</script>
The code adds multiple images and shows previews of the images too. But now I want that when a user clicks on some button, lets say delete on every image uploaded, it should be removed. Not hidden.
Any help to this will be appreciated!
Try adding this : .click(function(){$(this).remove();});. It will remove the image by clicking it.
EDIT Improved version included.
EDIT 2 Since people keep asking, please see this answer on manually deleting a file from a FileList (spoiler: it's not possible...).
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove image</span>" +
"</span>").insertAfter("#files");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){$(this).remove();});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
input[type="file"] {
display: block;
}
.imageThumb {
max-height: 75px;
border: 2px solid;
padding: 1px;
cursor: pointer;
}
.pip {
display: inline-block;
margin: 10px 10px 0 0;
}
.remove {
display: block;
background: #444;
border: 1px solid black;
color: white;
text-align: center;
cursor: pointer;
}
.remove:hover {
background: white;
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field" align="left">
<h3>Upload your images</h3>
<input type="file" id="files" name="files[]" multiple />
</div>
Use this for remove files values and file preview
$(".remove").click(function(){
$(this).parent(".pip").remove();
$('#files').val("");
});`
I am just trying to add code in this javascript to get values of slide to input type="hidden", but i can't get value into input type="hidden", what do I do wrong? Anyway, thanks for your help!
This is javascript code:
// <![CDATA[
var hWidth, bWidth;
function setBgPos(v) {
var off = v * hWidth;
var pos = -bWidth + (v * bWidth);
$('slider').setStyle({backgroundPosition: Math.round(pos - off) + 'px'});
}
function setSlideOutput(v) {
$('percent').innerHTML = Math.round(v * 100) + '%';
}
Event.observe(window, 'load', function() {
hWidth = $('slider-handle').getWidth();
bWidth = $('slider-bar').getWidth();
var slide = new Control.Slider('slider-handle', 'slider-bar', {
sliderValue: 0.25,
onSlide:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
},
onChange:
function(v) {
setBgPos(v);
setSlideOutput(v);
$('percentage').value = Math.round(v * 100) + '%';
}
});
setBgPos(slide.value);
setSlideOutput(slide.value);
});
// ]]>
Html:
<!DOCTYPE html>
<html lang="nl">
<head>
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/scriptaculous/1.9.0/scriptaculous.js"></script>
<style>
#slider, #slider-bar, #slider-handle {
border: 0;
padding: 0;
margin: 0;
}
#slider {
width: 300px;
height:42px;
background: url(img/bg.gif) no-repeat -300px;
margin-left: 42px;
}
#slider-bar {
width:300px;
height:42px;
background: url(img/track.png) no-repeat;
}
#slider-handle {
width:42px;
height:42px;
cursor:move;
background: url(img/gripper.png) no-repeat;
}
#percent {
font-size: 75%;
font-family: arial;
font-weight: bold;
text-align: center;
padding-top: 1.1em;
}
</style>
</head>
<body>
<div id="slider">
<div id="slider-bar">
<div id="slider-handle"><p id="percent"></p></div>
</div>
</div>
<input type="hidden" id="percentage" name="percentage" value="0" />
</body>
</html>
Try using $('#percentage')[0].value
What you need is DOM element, not jquery object.
Or, alternatively, use $('#percentage').val('')
you should use $('#percentage') instead of $('percentage')
UPDATE: Solved to add setvalue, this did help me: http://www.ruby-forum.com/topic/143329 . Thanks for all the tips guys and more thanks for Geek Num 88!
How can the code below be modified such that I would be able to add a centered "loading..." message inside the box while the progress bar runs in the background? Ie. it would display LOADING..." in the center of the box while the progress bar runs in the background inside the DIV.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var prg_width = 200;
var progress_run_id = null;
function progress() {
var node = document.getElementById('progress');
var w = node.style.width.match(/\d+/);
if (w == prg_width) {
clearInterval( progress_run_id );
w = 0;
alert("done")
} else {
w = parseInt(w) + 5 + 'px';
}
node.style.width = w;
}
function runit() {
progress_run_id = setInterval(progress, 30);
}
</script>
</head>
<body>
<div style="border: 1px solid #808080; width:200px; height:20px;">
<div id="progress" style="height:20px; width:0px; background-color:#DBDBDB;"/>
</div>
</div>
<p>Start</p>
</body>
</html>
<div style="border: 1px solid #808080; width:200px; height:20px;">
<div id="progress" style="text-align: center; height:20px; width:0px; background-color:#DBDBDB;"/>
<div style=" position: fixed; left: 92px ">loading</div>
</div>
</div>