Limit file format when using input type=file?
Strictly speaking, the answer is no. A developer cannot prevent a user from uploading files of any type or extension.
But still, the accept attribute of <input type = "file">
can help to provide a filter in the file select dialog box of the OS. For example,
<!-- (IE 10+, Edge (EdgeHTML), Edge (Chromium), Chrome, Firefox 42+) -->
<input type="file" accept=".xls,.xlsx" />
input type=file limit selectable files by extensions
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
How to limit the maximum files chosen when using multiple file input
You could run some jQuery client-side validation to check:
$(function(){
$("input[type='submit']").click(function(){
var $fileUpload = $("input[type='file']");
if (parseInt($fileUpload.get(0).files.length)>2){
alert("You can only upload a maximum of 2 files");
}
});
});
http://jsfiddle.net/Curt/u4NuH/
But remember to check on the server side too as client-side validation can be bypassed quite easily.
How to allow input type=file to accept only image files?
Use the accept attribute of the input tag. To accept only PNG's, JPEG's and GIF's you can use the following code:
<label>Your Image File
<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
</label>
Limit the size of a file upload (html input element)
This is completely possible. Use Javascript.
I use jQuery to select the input element. I have it set up with an onChange
event.
$("#aFile_upload").on("change", function (e) {
var count=1;
var files = e.currentTarget.files; // puts all files into an array
// call them as such; files[0].size will get you the file size of the 0th file
for (var x in files) {
var filesize = ((files[x].size/1024)/1024).toFixed(4); // MB
if (files[x].name != "item" && typeof files[x].name != "undefined" && filesize <= 10) {
if (count > 1) {
approvedHTML += ", "+files[x].name;
}
else {
approvedHTML += files[x].name;
}
count++;
}
}
$("#approvedFiles").val(approvedHTML);
});
The code above saves all the file names that I deem worthy of persisting to the submission page before the submission actually happens. I add the "approved" files to an input element's val using jQuery so a form submit will send the names of the files I want to save. All the files will be submitted, however, now on the server-side, we do have to filter these out. I haven't written any code for that yet but use your imagination. I assume one can accomplish this by a for loop and matching the names sent over from the input field and matching them to the $_FILES
(PHP Superglobal, sorry I don't know ruby file variable) variable.
My point is you can do checks for files before submission. I do this and then output it to the user before he/she submits the form, to let them know what they are uploading to my site. Anything that doesn't meet the criteria does not get displayed back to the user and therefore they should know, that the files that are too large won't be saved. This should work on all browsers because I'm not using the FormData
object.
How to filter input type=file dialog by specific file type?
See http://www.w3schools.com/tags/att_input_accept.asp:
The accept attribute is supported in all major browsers, except
Internet Explorer and Safari. Definition and UsageThe accept attribute specifies the types of files that the server
accepts (that can be submitted through a file upload).Note: The accept attribute can only be used with
<input type="file">
.Tip: Do not use this attribute as a validation tool. File uploads
should be validated on the server.Syntax
<input accept="audio/*|video/*|image/*|MIME_type" />
Tip: To specify more than one value, separate the values with a comma
(e.g.<input accept="audio/*,video/*,image/*" />
.
input type='file' always searches the input file in the path of the HTML file itself
You might want to do something like:
//<![CDATA[/* js/external.js */var doc, html, bod, nav, mobile, M, I, S, Q, aC, rC; // for use on other loadsaddEventListener('load', function(){doc = document; html = doc.documentElement; bod = doc.body; nav = navigator;mobile = nav.userAgent.match(/Mobi/i) ? true : false;M = function(tag){ return doc.createElement(tag);}I = function(id){ return doc.getElementById(id);}S = function(selector, within){ var w = within || doc; return w.querySelector(selector);}Q = function(selector, within){ var w = within || doc; return w.querySelectorAll(selector);}aC = function(element, className, yFunc){ var s = element.className.split(/\s+/), n = s.indexOf(className); if(n === -1){ s.push(className); element.className = s.join(' ').trim(); if(yFunc)yFunc(element); } return function(className, yFunc){ return aC(element, className, yFunc); }}rC = function(element, className, yFunc){ var s = element.className.split(/\s+/), n = s.indexOf(className); if(n !== -1){ s.splice(n, 1); element.className = s.join(' ').trim(); if(yFunc)yFunc(element); } return function(className, yFunc){ return rC(element, className, yFunc); }}// above is a mini-library - below could be on another page if you want - except the load endvar out = I('output');I('upload').onchange = function(){ if(this.files.length){ var file = this.files[0], img; // first file if(this.value.match(/\.(png|jpe?g|gif)$/i)){ // file.type is unreliable out.innerHTML = ''; rC(out, 'error'); img = M('img'); img.src = URL.createObjectURL(file); out.appendChild(img); } else{ aC(out, 'error'); out.innerHTML = 'Must Be An Image'; } }}}); // end load//]]>
/* css/external.css */*{ box-sizing:border-box; padding:0; margin:0;}html,body{ width:100%; height:100%;}body{ background:#ccc;}.main{ padding:5px 7px;}.error{ color:#900;}.hide{ display:none;}
<!DOCTYPE html><html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'> <head> <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' /> <title>Test Template</title> <link type='text/css' rel='stylesheet' href='css/external.css' /> <script src='js/external.js'></script> </head><body> <div class='main'> <input id='upload' type='file' /> <div id='output'></div> </div></body></html>
How to validade in HTML5 to only allow in 'input type=file' JPG, GIF or PNG?
Try something like
<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />
Click here for the latest browser compatibility table
Live demo here
To select only image files, you can use this accept="image/*"
<input type="file" name="my-image" id="image" accept="image/*" />
Live demo here
Only gif, jpg and png will be shown, screen grab from Chrome version 44
React: How to access file that gets passed in to html input type=file
EDITED: (removed setIsSelected(true);, its not needed)
I think you can use react states, it will make your life easier.
Try this one:
const [selectedFile, setSelectedFile] = useState();
const changeHandler = (event) => {
setSelectedFile(event.target.files[0]);
};
<input type="file" name="file" onChange={changeHandler} />
Your file will be in the selectedFile variable.
Related Topics
Html5 Number Input - Always Show 2 Decimal Places
How to Open a Link in New Tab Using Angular
Provide an Image for Whatsapp Link Sharing
How to Disable a Checkbox Based on Conditions in Angular 6
Select Option Padding Not Working in Chrome
How to Set Filename for Base64 Rendered Pdf Using Object Tag
How to Disable Auto-Play for Local Video in Iframe
Failed to Load Resource: the Server Responded With a Status of 404 (Not Found) CSS
Browsers Try to Download HTML File Instead of Opening
Limit Number of Digits After Decimals in Text Input
Directory Chooser in HTML Page
Does Ul Have Default Margin or Padding
How to Keep Two Side-By-Side Div Elements the Same Height
Post Unchecked HTML Checkboxes
How to Disable Equal Height Columns in Flexbox
What Are the Recommendations For HTML ≪Base≫ Tag
Htmlspecialchars() Expects Parameter 1 to Be String Array Given