Hello!
I wrote the single java script function to show the image preview before uploading.
For single file uploading, my code is working fine.
But now i want to give multiple image uploading options by giving multiple select options to user(see the snapshot). Also for this, i want to reuse my function that is displaying the preview of selected first image.(see the image in snapshot)
How would i modify my html code and how to reuse my script function?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" name="uploadedFile" type="file"/>
<input id="fileUpload2" name="" type="file"/>
<input id="fileUpload3" name="uploadedFile" type="file"/>
<div id="image-holder"></div>
</div>
</form>
Javascript
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
This is what classes are for. You are only calling your jQuery on the fileUpload Id. And if your going to use the same image holder for more than one image like this you should not be clearing it out each time.
I refactored your code a small amount. Try this.
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input class="fileUploadClass" id="fileUpload" name="uploadedFile" type="file"/>
<input class="fileUploadClass" id="fileUpload2" name="" type="file"/>
<input class="fileUploadClass" id="fileUpload3" name="uploadedFile" type="file"/>
<div id="image-holder"></div>
</div>
JavaScript
<script>
$(document).ready(function() {
$(".fileUploadClass").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
// image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
Related
html:
<form action="{{ path("image_gallery",{"id":id}) }}" method="post" enctype="multipart/form-data" >
<label for="files">Select multiple files: </label>
<input name="images[]" id="files" type="file" multiple/>
<input type="submit" name="submit" id="upload" value="submit" class="btn btn-fit-height green-soft" style="margin-top:10px" disabled />
</form>
<output id="result" style="display: -webkit-box;" />
jquery:
<script>
$('#files').change(function () {
var input = this;
var limit = 6;
var alreadyuploadedimage = '{{imagecount}}';
var allowedimage = limit - alreadyuploadedimage;
if (allowedimage == 0) {
this.value = '';
$('#msg').text("You can upload maximum 6 images and you have already uploaded 6 images.");
$(".requiredFieldsError").show();
$('#upload').attr('disabled', true);
}
if (allowedimage < parseInt(input.files.length)) {
this.value = '';
$('#msg').text("You can upload maximum 6 images and you have already uploaded " + alreadyuploadedimage + " images.please upload remaining images");
$(".requiredFieldsError").show();
$('#upload').attr('disabled', true);
}
if (parseInt(input.files.length) > 6) {
this.value = '';
$('#msg').text("Please upload maximum 6 images");
$(".requiredFieldsError").show();
$('#upload').attr('disabled', true);
}
for (i = 0; i < input.files.length; i++)
{
var ext = input.files[i].name.match(/\.(.+)$/)[1];
switch (ext) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
case 'JPG':
case 'JPEG':
case 'PNG':
case 'GIF':
$('#upload').attr('disabled', false);
$(".requiredFieldsError").hide();
break;
default:
this.value = '';
$('#msg').text("Please upload image with valid format");
$(".requiredFieldsError").show();
$('#upload').attr('disabled', true);
//alert('This is not an allowed file type.');
}
}
});
//Check File API support
if (window.File && window.FileList && window.FileReader)
{
var filesInput = document.getElementById("files");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++)
{
var file = files[i];
//Only pics
if (!file.type.match('image'))
continue;
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/>";
output.insertBefore(div, null);
});
//Read the image
picReader.readAsDataURL(file);
}
});
}
else
{
console.log("Your browser does not support File API");
}
</script>
once I have upload image (maximum allowed 6). and reload page again the file input is not cleared and it is upload again .how to clear file input after upload files ?
can any one help me for that?
Try adding:
<input name="images[]" id="files" value="" type="file" multiple/>
it will set the input to be empty by default every time is loaded.
I am using File Reader for selecting and uploading images.
My images are selected previewing but not uploaded when i hit submit button.
In upload.php the output of $_FILES is an empty array.
Where is problem?
html
<form action="upload.php" method="post" enctype="multipart/form-data">
<div id="wrapper" style="margin-top: 20px;">
<input id="fileUpload" multiple="multiple" type="file"/>
<input type="submit" value="Upload Image" name="upload">
<div id="image-holder">
</div>
</div>
</form>
Javascript
<script>
$(document).ready(function() {
$("#fileUpload").on('change', function() {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++)
{
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
});
</script>
upload.php
<?php
require_once './include/db_connection.php';
if(isset($_POST['upload']))
{
print_r($_FILES);
die();
if(!empty($_FILES)){
$targetDir = "upload/";
$fileName = $_FILES['file']['name'];
$targetFile = $targetDir.$fileName;
if(move_uploaded_file($_FILES['file']['tmp_name'],$targetFile))
{
//insert file information into db table
$sql = mysqli_query($link,"INSERT INTO files (file_name, uploaded) VALUES('".$fileName."','".date("Y-m-d H:i:s")."')");
echo 'file inserted';
}
else
{
echo 'Query not working';
}
}
else
{
echo 'No file selected';
}
}
Your file input doesn't have a name.
The name of a form control is used to determine what key it will have in the submitted data. Controls without them will not be successful (i.e. will not appear in the submitted data at all).
I have a JavaScript function that shows me the previews of the images I want to upload to the server. After recieving that previews I can select some of them by clicking and remove previews, but I need also to remove the selected files so they will not be uploaded to the server.
The following code can remove the previews but not the files. How can it be improved?
JavaScript:
$(document).ready(function () {
$("#image-holder").on('click', '.thumb-image', function () {
$(this).toggleClass("selectedItem");
});
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
});
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof(FileReader) != "undefined") {
//loop for each file selected for uploading.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
};
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Please select only images");
}
});
});
HTML:
<form method="POST" action="upload" enctype="multipart/form-data">
<input id="fileUpload" name="file" multiple="multiple" type="file"/>
<br/>
<input type="submit" value="Upload">
</form>
<button id="btnDelete">Delete</button>
I've done this before using AngularJS. In that case I just had to set the ng-model variable to undefined. I haven't tested this, but you should be able to accomplish the same thing by clearing your <input> value in a similar way.
$("#btnDelete").on("click", function () {
$(".selectedItem").remove();
$("#fileUpload").get(0).files[0] = undefined;
$("#fileUpload").removeAttr('value');
});
I am triggering a file upload on href click.
I am trying to block all extension except doc, docx and pdf.
I am not getting the correct alert value.
<div class="cv"> Would you like to attach you CV? Click here</div>
<input type="file" id="resume" style="visibility: hidden">
Javascript:
var myfile="";
$('#resume_link').click(function() {
$('#resume').trigger('click');
myfile=$('#resume').val();
var ext = myfile.split('.').pop();
//var extension = myfile.substr( (myfile.lastIndexOf('.') +1) );
if(ext=="pdf" || ext=="docx" || ext=="doc"){
alert(ext);
}
else{
alert(ext);
}
})
MyFiddle..its showing error
You can use
<input name="Upload Saved Replay" type="file"
accept="application/pdf,application/msword,
application/vnd.openxmlformats-officedocument.wordprocessingml.document"/>
whearat
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
instead.
[EDIT] Be warned, .dot might match too.
Better to use change event on input field.
Updated source:
var myfile="";
$('#resume_link').click(function( e ) {
e.preventDefault();
$('#resume').trigger('click');
});
$('#resume').on( 'change', function() {
myfile= $( this ).val();
var ext = myfile.split('.').pop();
if(ext=="pdf" || ext=="docx" || ext=="doc"){
alert(ext);
} else{
alert(ext);
}
});
Updated jsFiddle.
For only acept files with extension doc and docx in the explorer window try this
<input type="file" id="docpicker"
accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document">
Below code worked for me:
<input #fileInput type="file" id="avatar" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" />
application/pdf means .pdf
application/msword means .doc
application/vnd.openxmlformats-officedocument.wordprocessingml.document means .docx
Try this
$('#resume_link').click(function() {
var ext = $('#resume').val().split(".").pop().toLowerCase();
if($.inArray(ext, ["doc","pdf",'docx']) == -1) {
// false
}else{
// true
}
});
Hope it will help
var file = form.getForm().findField("file").getValue();
var fileLen = file.length;
var lastValue = file.substring(fileLen - 3, fileLen);
if (lastValue == 'doc') {//check same for other file format}
$('#surat_lampiran').bind('change', function() {
alerr = "";
sts = false;
alert(this.files[0].type);
if(this.files[0].type != "application/pdf" && this.files[0].type != "application/msword" && this.files[0].type != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
sts = true;
alerr += "Jenis file bukan .pdf/.doc/.docx ";
}
});
You can simply make it by REGEX:
Form:
<form method="post" action="" enctype="multipart/form-data">
<div class="uploadExtensionError" style="display: none">Only PDF allowed!</div>
<input type="file" name="item_file" />
<input type="submit" id='submit' value="submit"/>
</form>
And java script validation:
<script>
$('#submit').click(function(event) {
var val = $('input[type=file]').val().toLowerCase();
var regex = new RegExp("(.*?)\.(pdf|docx|doc)$");
if(!(regex.test(val))) {
$('.uploadExtensionError').show();
event.preventDefault();
}
});
</script>
Cheers!
if(req.file){
let img = req.file ;
if(img.mimetype != "application/pdf" && img.mimetype != "application/msword" && img.mimetype != "application/vnd.openxmlformats-officedocument.wordprocessingml.document"){
throw {message :"Please enter only pdf and docx file"}
}
}
HTML code:
<input type="file" multiple={true} id="file" onChange={this.addFile.bind(this)} accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.ppt, .pptx"/>
React code - file attached and set files in state:
#autobind
private addFile(event) {
for(var j=0;j<event.target.files.length;j++){
var _size = event.target.files[j].size;
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB'),
i=0;while(_size>900){_size/=1024;i++;}
var exactSize = (Math.round(_size*100)/100)+' '+fSExt[i];
var date = event.target.files[0].lastModifiedDate,
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
date=[day,mnth,date.getFullYear()].join("/");
fileinformation.push({
"file_name": event.target.files[j].name,
"file_size": exactSize,
"file_modified_date":date
});
var ext = event.target.files[j].name.split('.').pop();
if(ext=="pdf" || ext=="docx" || ext=="doc"|| ext=="ppt"|| ext=="pptx"){
} else{
iscorrectfileattached=false;
}
}
if(iscorrectfileattached==false){
alert("Only PFD, Word and PPT file can be attached.");
return false;
}
this.setState({fileinformation});
//new code end
var date = event.target.files[0].lastModifiedDate,
mnth = ("0" + (date.getMonth() + 1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
date=[day,mnth,date.getFullYear()].join("/");
this.setState({filesize:exactSize});
this.setState({filedate:date});
//let resultFile = document.getElementById('file');
let resultFile = event.target.files;
console.log(resultFile);
let fileInfos = [];
for (var i = 0; i < resultFile.length; i++) {
var fileName = resultFile[i].name;
console.log(fileName);
var file = resultFile[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
//Push the converted file into array
fileInfos.push({
"name": file.name,
"content": e.target.result
});
};
})(file);
reader.readAsArrayBuffer(file);
}
this.setState({fileInfos});
this.setState({FileNameValue: event.target.files[0].name });
//this.setState({IsDisabled: true });//for multiple file
console.log(fileInfos);
}
In my HTML form I have input filed with type file for example :
<input type="file" multiple>
Then I'm selecting multiple files by clicking that input button.
Now I want to show preview of selected images before submitting form . How to do that in HTML 5?
Here's a quick example that makes use of the URL.createObjectURL to render a thumbnail by setting the src attribute of an image tag to a object URL:
The html code:
<input accept="image/*" type="file" id="files" />
<img id="image" />
The JavaScript code:
document.getElementById('files').onchange = function () {
var src = URL.createObjectURL(this.files[0])
document.getElementById('image').src = src
}
The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:
function handleFileSelect (evt) {
// Loop through the FileList and render image files as thumbnails.
for (const file of evt.target.files) {
// Render thumbnail.
const span = document.createElement('span')
const src = URL.createObjectURL(file)
span.innerHTML =
`<img style="height: 75px; border: 1px solid #000; margin: 5px"` +
`src="${src}" title="${escape(file.name)}">`
document.getElementById('list').insertBefore(span, null)
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" accept="image/*" id="files" multiple />
<output id="list"></output>
Here I did with jQuery using FileReader API.
Html Markup:
<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>
jQuery:
Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message
$("#fileUpload").on('change', function () {
//Get count of selected files
var countFiles = $(this)[0].files.length;
var imgPath = $(this)[0].value;
var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
var image_holder = $("#image-holder");
image_holder.empty();
if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
if (typeof (FileReader) != "undefined") {
//loop for each file selected for uploaded.
for (var i = 0; i < countFiles; i++) {
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[i]);
}
} else {
alert("This browser does not support FileReader.");
}
} else {
alert("Pls select only images");
}
});
function handleFileSelect(evt) {
var files = evt.target.files;
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML =
[
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="',
e.target.result,
'" title="', escape(theFile.name),
'"/>'
].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
<input type="file" id="files" multiple />
<output id="list"></output>
For background images, make sure to use url()
node.backgroundImage = 'url(' + e.target.result + ')';
Without FileReader, we can use URL.createObjectURL method to get the DOMString that represents the object ( our image file ).
Don't forget to validate image extension.
<input type="file" id="files" multiple />
<div class="image-preview"></div>
let file_input = document.querySelector('#files');
let image_preview = document.querySelector('.image-preview');
const handle_file_preview = (e) => {
let files = e.target.files;
let length = files.length;
for(let i = 0; i < length; i++) {
let image = document.createElement('img');
// use the DOMstring for source
image.src = window.URL.createObjectURL(files[i]);
image_preview.appendChild(image);
}
}
file_input.addEventListener('change', handle_file_preview);