jQuery script code:
$(function() {
$('#html_btn1').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview1(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
$('#html_btn2').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview2(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
$('#html_btn3').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview3(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview1(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu1').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
function showimagepreview2(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu2').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
function showimagepreview3(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu3').attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
HTML markup:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="html_btn3" />
</div>
Above code works fine whenever I am trying to upload image it checks validate and preview the image
But I want to minimize my code as only one change function and only one showimagepreview function
Please give me an idea how to achieve?
#Huangism is correct, this should probably be on codereview. But, for the sake of helping:
$(function() {
// combine binding selector in to one
$('#html_btn1,#html_btn2,#html_btn3').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview(this); break; // change to single "showimagepreview" function
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview(input) {
// grab "cu#" using the original element's id
var cu_id = '#cu' + input.id.match(/\d+$/)[0];
/* alt: var cu_id = input.id.replace('html_btn','#cu'); */
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
// reference id here
$(cu_id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
Combine your bindings in to one using a comma-separated selector
Remove the duplicated showimagepreview# methods and unify into one function
Change hard-coded cu# ids in to a dynamic id based on the original input's ID.
Reference that id in the selector.
Would it not be easier to use a class? As long as you are keeping the scope by using 'this'
You should be fine to have two generic functions like so
$('.addClassToImages').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' :
case 'gif' :
case 'jpeg' : showimagepreview3(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview1(input) {
var cu_id = '#cu' + input.id.match(/\d+$/)[0];
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$(cu_id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
HTML:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input class="addClassToImages" type="file" path="images" id="html_btn3" />
</div>
Javascript:
$(function() {
$('input[type=file]').change(function(){
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.')+1).toLowerCase()){
case 'jpg' :
case 'png' : showimagepreview(this); break;
case 'gif' :
case 'jpeg' : showimagepreview(this); break;
default : $('#errorimg').html("Invalid Photo"); break;
}
});
function showimagepreview(input) {
if (input.files && input.files[0]) {
var filerdr = new FileReader();
filerdr.onload = function(e) {
$('#cu'+input.id).attr('src', e.target.result);
};
filerdr.readAsDataURL(input.files[0]);
}
}
});
HTML:
<div class="form-group">
<img id="cu1" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="1" />
<img id="cu2" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="2" />
<img id="cu3" src="upload-photo-img.jpg"/>
<input type="file" path="images" id="3" />
EDIT - UPDATED LINK
http://jsfiddle.net/S4mk2/
And... yes as Brad Christie mentioned, this would be ideal for HTML5
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 need to change the background image inside of canvas with the leimi drawingboard.js, but I have no idea how to make it.
I need to show different images so that the user can choose between them with which he is going to work
Here is my form:
<div id="container">
<div class="example" data-example="1"> // THIS DIV IS THE CANVAS
<div class="board" id="default-board"></div> //THIS ID HAVE A IMAGE AND THE CONTROLLERS
</div>
<form class="drawing-form" method="post" name="diagram" id="diagram" enctype="multipart/form-data">
<div id="board"></div>
<input type="hidden" name="image" value="">
<input type="hidden" name="idPac" value="<?php echo $id_paciente; ?>" />
<input type="hidden" name="idDoc" value="<?php echo $user_id; ?>" />
<br><hr>
<button class="btn btn-info" id="btnUpload"><?php $translate->__('Save Diagram'); ?></button>
</form>
<div id="ldiag" style="display:none;"><img src="images/loading4.gif" /></div>
</div>
And the javascript code is:
<script src="js/drawingboard.min.js"></script>
<script data-example="1">
var defaultBoard = new DrawingBoard.Board("default-board", {
background: "imagenes/canvas/cara.jpg", //THIS IS THE IMAGE I NEED TO CHANGE FOR OTHERS IF NEEDED, EXAMPLE /pie.png, /cuerpo.png
droppable: true,
webStorage: false,
enlargeYourContainer: true,
addToBoard: true,
stretchImg: false
});
defaultBoard.addControl("Download");
$(".drawing-form").on("submit", function(e) {
var img = defaultBoard.getImg();
var imgInput = (defaultBoard.blankCanvas == img) ? "" : img;
$(this).find("input[name=image]").val( imgInput );
defaultBoard.clearWebStorage();
});
$(function() {
$("#file-input").change(function(e) {
var file = e.target.files[0],
imageType = /image.*/;
if (!file.type.match(imageType))
return;
var reader = new FileReader();
reader.onload = fileOnload;
reader.readAsDataURL(file);
});
function fileOnload(e) {
var $img = $("<img>", { src: e.target.result });
var canvas = $("#default-board")[0];
var context = canvas.getContext("2d");
$img.load(function() {
context.drawImage(this, 0, 0);
});
}
});
</script>
<script src="js/yepnope.js"></script>
<script>
var iHasRangeInput = function() {
var inputElem = document.createElement("input"),
smile = ":)",
docElement = document.documentElement,
inputElemType = "range",
available;
inputElem.setAttribute("type", inputElemType);
available = inputElem.type !== "text";
inputElem.value = smile;
inputElem.style.cssText = "position:absolute;visibility:hidden;";
if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
available = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== "textfield" &&
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
}
return !!available;
};
yepnope({
test : iHasRangeInput(),
nope : ["css/fd-slider.min.css", "js/fd-slider.min.js"],
callback: function(id, testResult) {
if("fdSlider" in window && typeof (fdSlider.onDomReady) != "undefined") {
try { fdSlider.onDomReady(); } catch(err) {}
}
}
});
</script>
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 tried different approach but still can't find the solution.
I need to upload an image with my form with fields (title, description, and 2 image).
My system uses csrf of CodeIgniter. And I use this simple third party file uploader (http://jasny.github.io/bootstrap) fileinput.js
var Fileinput = function (element, options) {
this.$element = $(element)
this.$input = this.$element.find(':file')
if (this.$input.length === 0) return
this.name = this.$input.attr('name') || options.name
this.$hidden = this.$element.find('input[type=hidden][name="' + this.name + '"]')
if (this.$hidden.length === 0) {
this.$hidden = $('<input type="hidden">').insertBefore(this.$input)
}
this.$preview = this.$element.find('.fileinput-preview')
var height = this.$preview.css('height')
if (this.$preview.css('display') !== 'inline' && height !== '0px' && height !== 'none') {
this.$preview.css('line-height', height)
}
this.original = {
exists: this.$element.hasClass('fileinput-exists'),
preview: this.$preview.html(),
hiddenVal: this.$hidden.val()
}
this.listen()
}
Fileinput.prototype.listen = function() {
this.$input.on('change.bs.fileinput', $.proxy(this.change, this))
$(this.$input[0].form).on('reset.bs.fileinput', $.proxy(this.reset, this))
this.$element.find('[data-trigger="fileinput"]').on('click.bs.fileinput', $.proxy(this.trigger, this))
this.$element.find('[data-dismiss="fileinput"]').on('click.bs.fileinput', $.proxy(this.clear, this))
},
Fileinput.prototype.change = function(e) {
var files = e.target.files === undefined ? (e.target && e.target.value ? [{ name: e.target.value.replace(/^.+\\/, '')}] : []) : e.target.files
e.stopPropagation()
if (files.length === 0) {
this.clear()
return
}
this.$hidden.val('')
this.$hidden.attr('name', '')
this.$input.attr('name', this.name)
var file = files[0]
if (this.$preview.length > 0 && (typeof file.type !== "undefined" ? file.type.match(/^image\/(gif|png|jpeg)$/) : file.name.match(/\.(gif|png|jpe?g)$/i)) && typeof FileReader !== "undefined") {
var reader = new FileReader()
var preview = this.$preview
var element = this.$element
reader.onload = function(re) {
var $img = $('<img>')
$img[0].src = re.target.result
files[0].result = re.target.result
element.find('.fileinput-filename').text(file.name)
// if parent has max-height, using `(max-)height: 100%` on child doesn't take padding and border into account
if (preview.css('max-height') != 'none') $img.css('max-height', parseInt(preview.css('max-height'), 10) - parseInt(preview.css('padding-top'), 10) - parseInt(preview.css('padding-bottom'), 10) - parseInt(preview.css('border-top'), 10) - parseInt(preview.css('border-bottom'), 10))
preview.html($img)
element.addClass('fileinput-exists').removeClass('fileinput-new')
element.trigger('change.bs.fileinput', files)
}
reader.readAsDataURL(file)
} else {
this.$element.find('.fileinput-filename').text(file.name)
this.$preview.text(file.name)
this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
this.$element.trigger('change.bs.fileinput')
}
},
Fileinput.prototype.clear = function(e) {
if (e) e.preventDefault()
this.$hidden.val('')
this.$hidden.attr('name', this.name)
this.$input.attr('name', '')
//ie8+ doesn't support changing the value of input with type=file so clone instead
this.$input.val('')
this.$preview.html('')
this.$element.find('.fileinput-filename').text('')
this.$element.addClass('fileinput-new').removeClass('fileinput-exists')
if (e !== undefined) {
this.$input.trigger('change')
this.$element.trigger('clear.bs.fileinput')
}
},
Fileinput.prototype.reset = function() {
this.clear()
this.$hidden.val(this.original.hiddenVal)
this.$preview.html(this.original.preview)
this.$element.find('.fileinput-filename').text('')
if (this.original.exists) this.$element.addClass('fileinput-exists').removeClass('fileinput-new')
else this.$element.addClass('fileinput-new').removeClass('fileinput-exists')
this.$element.trigger('reset.bs.fileinput')
},
Fileinput.prototype.trigger = function(e) {
this.$input.trigger('click')
e.preventDefault()
}
// FILEUPLOAD PLUGIN DEFINITION
// ===========================
var old = $.fn.fileinput
$.fn.fileinput = function (options) {
return this.each(function () {
var $this = $(this),
data = $this.data('bs.fileinput')
if (!data) $this.data('bs.fileinput', (data = new Fileinput(this, options)))
if (typeof options == 'string') data[options]()
})
}
$.fn.fileinput.Constructor = Fileinput
// FILEINPUT NO CONFLICT
// ====================
$.fn.fileinput.noConflict = function () {
$.fn.fileinput = old
return this
}
// FILEUPLOAD DATA-API
// ==================
$(document).on('click.fileinput.data-api', '[data-provides="fileinput"]', function (e) {
var $this = $(this)
if ($this.data('bs.fileinput')) return
$this.fileinput($this.data())
var $target = $(e.target).closest('[data-dismiss="fileinput"],[data-trigger="fileinput"]');
if ($target.length > 0) {
e.preventDefault()
$target.trigger('click.bs.fileinput')
}
});
Now here is my form:
<form id="default_form" onsubmit="return false;" data-method="websites" enctype="multipart/form-data" data-toastr-position="top-right" data-success="Sent! Thank you!" class="validate" novalidate="novalidate">
<input type="hidden" name="{$my_csrf_name}" id="csrf" value="{$my_csrf_value}" />
<input type="text" class="form-control required" value="" name="d[DEF_TITLE]" id="MY_TITLE">
<textarea class="form-control required" rows="3" name="d[MY_DESC]" id="MY_DESC"></textarea>
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail" style="min-width: 160px; min-height: 100px; max-width: 200px; max-height: 150px; line-height: 10px;"> <img src="{$_homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" alt="{$homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" data-src="{$homeurl}space/perm/img/favicon/{$set_data.MY_FAVICON}" > </div>
<div class="fileinput-preview fileinput-exists thumbnail" style="max-width: 200px; max-height: 150px;"></div>
<div>
<span class="btn btn-default btn-file" class="upload-image">
<span class="fileinput-new">Select Favicon image</span>
<span class="fileinput-exists">Change</span>
<input type="file" id="MY_FAVICON" name="d[MY_FAVICON]"></span>
Remove
</div>
</div>
<button id="submit_form" data-fid="default_form" class="btn btn-3d btn-primary btn-xlg btn-block margin-top-30" type="submit">
SUBMIT
</button>
</form>
Now upon clicking the "Select Favicon image" here is my js code event:
var csrf_val = $('#csrf').val();
var csfrData = {};
csfrData['csrf_name'] = csrf_val;
sendFile(this.files[0]);
function sendFile(file) {
$(function() {
$.ajaxSetup({
data: csfrData
});
});
$.ajax({
method: 'post',
url: _admin_url + _curr_mod+'/procedure/uload-image',
data: file,
success: function() {
alert('upload is ok!');
},
processData: false
});
}
upon select of image the JavaScript will process to upload the image in PHP controller/model. As I try to look into the Firebug the post has this values:
ÿØÿà�JFIF������ÿÛ��
Then in the response tab found in the CodeIgniter was this (this might be because of the csrf is not included in the post data):
An Error Was Encountered
The action you have requested is not allowed.
and for the php will just use this code (still not sure how will I handle it in php):
$_FILES['file']
I don't know how to upload an image using an uploader (that has preview of the file) and with csrf in CodeIgniter.
The process is this, upon select of image, an ajax will upload it to the server (temporary folder), and will return a new filename (encryption enabled upon upload in php)
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);
}