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);
}
Related
I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo
I created a very basic example of a multiple file upload form (reference), it works perfect on desktop but not on mobile, at least the ones I am testing with.
On Mobile (Xiaomi Mi4 [Android version: 6.1] - Google Chrome/Mozilla Firefox): When I click on Choose files I see this screen:
If I choose Google Photos and select multiple files, only the first file will be inserted into the form.
If I select the Gallery (native) app and select multiple files I get the correct number on the form but when I click upload I get the "Aw Snap" screen:
Any idea why this is happening?
Besides Google Photos and the native app I tried 5 different apps, the last one, Piktures actually worked!
Please tell me this is not an app thing... is there a way to get the files correctly?
Code attached:
<form method="post" enctype="multipart/form-data">
<input type="file" name="my_file[]" multiple>
<input type="submit" value="Upload">
</form>
<?php
if (isset($_FILES['my_file'])) {
$myFile = $_FILES['my_file'];
$fileCount = count($myFile["name"]);
for ($i = 0; $i < $fileCount; $i++) {
?>
<p>File #<?= $i+1 ?>:</p>
<p>
Name: <?= $myFile["name"][$i] ?><br>
Temporary file: <?= $myFile["tmp_name"][$i] ?><br>
Type: <?= $myFile["type"][$i] ?><br>
Size: <?= $myFile["size"][$i] ?><br>
Error: <?= $myFile["error"][$i] ?><br>
</p>
<?php
}
}
?>
If you wish to test: http://odedta.com/projects/jqueryfileupload/
Thanks!
Try this might help you this is only front end part of file upload with js
window.onload = function() {
if (window.File && window.FileList && window.FileReader) {
var filesInput = document.getElementById("uploadImage");
filesInput.addEventListener("change", function(event) {
var files = event.target.files;
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
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);
});
picReader.readAsDataURL(file);
}
});
}
}
<input type="file" id="uploadImage" name="termek_file" class="file_input" multiple/>
<div id="result" class="uploadPreview">
I am not sure exactly about that mobile browsers are support multiple attribute I read some article it is not support or is not standart, any way If you want to post multiple image; You can see full code below
First Step;
You should use FileReader for load on browser as locally
Multiple file loading with FileReader
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
//Filename listing
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
//FileReader create and set onload event
var reader = new FileReader();
reader.onload = function (data) {
data.target.result;
}
//Read file
reader.readAsDataURL(input.files[x]);
}
}
Second Step
You can set image content to textarea as base64 data for each file
reader.onload = function (data) {
//....
//Split base64 data from DataURL (// "data:image/png;base64,.....)
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
//...
}
Third Step
Then you can send to your php file whole data and save your content as image
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
//decode base64 content and put file
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
Full Code
HTML & JavaScript
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple />
<form method="post" action="multipleFileUpload.php" enctype="multipart/form-data" id="formMultipleFileUpload">
<ul id="fileList">
</ul>
<input type="submit" value="Upload" id="btnUpload">
</form>
<script type="text/javascript">
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
document.getElementById("filesToUpload").onchange = function () {
var fileIndex = 0;
for ( var x= 0; x < input.files.length; x++) {
//add to list
var li = document.createElement('li');
li.setAttribute('id','li_'+x);
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
var reader = new FileReader();
reader.onload = function (data) {
var li = document.getElementById('li_'+fileIndex);
var previewImg = document.createElement('img');
previewImg.setAttribute('width','50');
previewImg.setAttribute('height','50');
li.append(previewImg);
previewImg.src = data.target.result;
var b64 = data.target.result.split(',')[1];
var b64Input = document.createElement('textarea');
b64Input.setAttribute('name','file64[]');
b64Input.value = b64;
li.append(b64Input);
var fileName = document.createElement('input');
fileName.setAttribute('name','fileName[]');
fileName.value = input.files[fileIndex].name;
li.append(fileName);
fileIndex++;
}
reader.readAsDataURL(input.files[x]);
}
}
PHP (multipleFileUpload.php)
<?php
for($i = 0; $i<count($_POST["fileName"]);$i++){
echo $_POST["fileName"][$i]."<br>";
file_put_contents($_POST["fileName"][$i], base64_decode($_POST["file64"][$i]));
}
?>
Working screenshot
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 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 was hoping someone can update this JSFiddle code for me so that multiple input boxes appear for multiple selected images.
It works perfectly for for a Single image.
https://jsfiddle.net/WWNnV/609/
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var filename = this.value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
document.getElementById('filename').value = filename + "_date";
}
<input id="upload" type="file" multiple="multiple" />
<input id="filename" type="text" />
Any assistance will be appreciated.
#Anoop and #dandavis were right. Without jQuery and keeping the behaviour if it's one file then something like this:
document.getElementById('upload').onchange = uploadOnChange;
function uploadOnChange() {
var text = this.value;
if (this.files && this.files.length > 1) {
var filenames = [];
for(i=0; i<this.files.length; i++) {
var filename = this.files[i].name;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
filenames.push(filename);
}
text = filenames.join();
}
document.getElementById('filename').value = text;
}
JSFiddle: https://jsfiddle.net/bartvanderwal/Lego5bcp/4/
TODO: Create multiple input instead of concatenating filenames
Updated jsfiddle
Changed jQuery version.
Use this.files instead of this.value to get all files selected by user.