Showing only XML files in HTML file input element - javascript

How can I show only XML files in a file input element?
I read about the "accept" attribute but also learned no browser actually support it. I found here some JS scripts but they didn't work well :-\
(I'm checking this server side as well but would like to do it client side too)
Thanks

The answer is pretty simple, you use the MIME type. So if it is an xml file you want, you just do:
<input type="file" accept="text/xml" />
If you want to see the full list of MIME types, check this site http://www.iana.org/assignments/media-types/media-types.xhtml

Not sure if you can do that, but at least you could use a callback function and check the input value for the .xml extension.
Snippet:
<script type="text/javascript">
function isXml(input)
{
var value = input.value;
var res = value.substr(value.lastIndexOf('.')) == '.xml';
if (!res) {
input.value = "";
}
return res;
}
</script>
<form method="post" action="">
<input type="file" name="myfile" id="myfile" onchange="return isXml(this)" />
<input type="submit" />
</form>

Related

HTML file input with possibility to input several files one after another

I'm looking for a possibility to input several files in a row in an HTML form. It strikes me that there seems to be no easy solution for this (or at least I haven't been able to find it despite several hours of searching). If I use the multiple attribute in an <input type="file" name="myFiles[]" multiple />, I can choose several files at a time holding Ctrl, but if I choose one file at first, then click the input field again and choose another one, the second file seems to overwrite the first one.
So I thought I might try to use javascript to add more <input type="file" name="myFiles[]" /> fields (with the same name), since I have seen something similar somewhere. I tried the following:
JavaScript:
function addInputFileEle() {
var field = document.getElementById("filesField");
var row = '<input type="file" name="myFiles[]" onchange="addInputFileEle();" />';
field.innerHTML += row; // add one more <input type="file" .../> element
}
HTML:
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesField"> <!--for adding more file-input rows-->
<input type="file" multiple name="myFiles[]" class="multi" onchange="addInputFileEle();" />
</fieldset>
<input type="submit"/>
</form>
The document indeed does create additional file-input elements whenever I click on one of them and select a file, BUT: The file does not get uploaded! I mean, after I select the file, the file name does not get displayed, instead, it still says "Choose a file" (or "Select a file", not sure about English). So apparently my onchange="addInputFileEle()" overwrites the normal reaction (the file getting 'loaded' into the input element)? Even though this does not seem logical to me. Can anyone help? Why does the file not get selected in the end? Or maybe there is a simpler solution than mine, which would of course be very welcome. Thanks in advance!
Ok I will just post my solution in case anyone else is searching for a way to select several files for upload one by one. As #CodingWithClass pointed out, I was resetting the input field by using something like parentElement.innerHTML += additionalInputElement;. Instead, I should have used appendChild as #JoshuaK suggested:
<html>
<head>
<meta charset="UTF-8">
<script>
function addFileInput(fieldsetName, firstInputId) {
var fs = document.getElementById(fieldsetName);
// only add one if the last file-input field is not empty
if(fs.lastElementChild.value != '') {
var firstInputFile = document.getElementById(firstInputId);
var newInputFile = document.createElement("input");
newInputFile.type = firstInputFile.type;
newInputFile.name=firstInputFile.name;
newInputFile.multiple=firstInputFile.multiple;
newInputFile.class = firstInputFile.class;
newInputFile.onchange=firstInputFile.onchange;
fs.appendChild(newInputFile);
}
}
</script>
<title>MultiFile-Testing</title>
</head>
<body>
<?php print_r($_FILES); // see if files were uploaded in the previous round ?>
<form method="post" action="#" enctype="multipart/form-data">
<fieldset id="filesFS">
<input type="file" multiple name="myFiles[] id="firstInputFile" onchange="addFileInput('filesFS', 'firstInputFile');" />
</fieldset>
<input type="submit"/>
</form>
</body>
</html>

Trying to get the full url of input file

All I get is the images name not the file tree like
C:/document/picture/dangit.gif
Okay, I need to add more text for some reason because stack overflow thinks that I should type more then I need to type so just ignore this text this is so retarded.
<html>
<head>
<script>
function getData() {
var text = document.getElementById("textarea").value;
var text = text.replace(/\r?\n/g, "<br />");
document.getElementById("display").innerHTML = text;
}
function picture() {
var picture = document.getElementById("picture").value;
document.getElementById("pDisplay").src = picture;
document.getElementById("purl").innerHTML = picture;
}
</script>
<title>Gettings a textbox formatting</title>
</head>
<body>
<textarea id="textarea" onkeypress="getData()" autofocus></textarea>
<p id="display">You havnt typed anything yet</p>
<input type="file" id="picture" />
<button onclick="picture()">get the picture from the box</button>
<p id="purl">picture url</p>
<img id="pDisplay" />
</body>
</html>
That's impossible because javascript can't access local storage like hard disk.
The only option is to upload image to the server and then reference it with URL.
If you are using PHP you could start with the documentation http://www.php.net/manual/en/features.file-upload.php
And you need to enclose your <input type="file"> with <form> and provide <input type="submit"> to send the file to the server.
This is not possible due to security restrictions. JavaScript in browser has no access to the File System.
It doesn't work on any of the main browsers (except IE) for security related restrictions

filter file upload for only text files

I am using Firefox version 14.0.1. I need to filter the upload file window to show up only .txt files.
My browser is not supporting only for text files(text/plain). I can restrict image files by specifying this format ("image/*"). But I need to filter only text files in File Selector window.
Is there any problem with my browser?
Simply do this...
$("#form").submit(function(e) {
e.preventDefault();
var checkUploadFileExtension = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '').split('.').pop();
if(checkUploadFileExtension === 'txt') {
alert("Success Uploaded!");
//Do Something
} else {
alert("Please upload text file only");
//Show error
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form" name="form" method="post">
<input name="file" id="file" type="file" accept="text/*" />
<button class="btn operations-btn btn-default" id="submit">Upload</button>
</form>
I hope, will help my post. Thank you
So according to the MDN reference on the input element accept=[MIME Type] is unimplemented in Gecko and currently you can only do : accept=image|audio|video
One way you could do this is a server side check for the type on the asp.net-mvc controller.
But a nicer way would be to do it on the client with some javascript: Something like this:
<script>
function checkExt() {
if(document.mainForm.myfile.value.lastIndexOf(".txt")==-1) {
alert("Please upload only .txt extention file");
return false;
}
}
</script>
<form name="mainForm">
<input type="file" name="myfile" onchange="checkExt();"/>
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
See it running here:
http://jsfiddle.net/Egr9V/
If your using JQuery you could make your code slicker or use the Validation plugin as described in this post:
How to have jQuery restrict file types on upload?

Validate at least 1 file input is completed with jQuery

How can I ensure that at least one field has a selected file using jQuery? Here is my form:
<form action="b.php">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="file" name="file[]">
<input type="submit" value="Value">
</form>
To achieve this you can use map() to build an array of all the valid file input elements. You can then check if this array has any elements in it. If it does, then at least one input was valid, if it was empty then nothing has been chosen. Try this:
var validFields = $('input[type="file"]').map(function() {
if ($(this).val() != "") {
return $(this);
}
}).get();
if (validFields.length) {
console.log("Form is valid");
} else {
console.log("Form is not valid");
}
Example fiddle
You could use jQuery's .val() method to check if a value has been set but I don't know if that works for file input types.
However, you should use a server-side language to validate your files because if you're using javascript, the person browsing the page can just disable the validating. Just loop through the file[] array and check if it's empty or not.
This is much safer and easier as well actually.
While you of course need server-side validation, there are some nice tricks to check if somebody has added a file to your input elements.
Now, your access to the file input element is heavily restricted due to security reasons, so you can't for example change it. You can, however, check the following:
if($('input[type="file"]').val() != "") {
alert("a file is selected")
}

Get files from input.files instead of value on submit

I have following problem. I have input field in form, type of file:
<FORM action="http://server.com/cgi/handle"
enctype="multipart/form-data"
method="post">
<P>
What is your name? <INPUT type="text" name="submit-name"><BR>
What files are you sending? <INPUT type="file" name="files"><BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</FORM>
I am setting using JavaScript also files property of this input and I want this input on submit of form send the file property instead of his value. Is it possible to do so?
var data = e.dataTransfer;
var input = dojo.byId(inputName);
var file = data.files[i];
input.files[0] = file;
data is a datatransfer object, I am getting files from there.
I know, it will be possible only in few browsers, I dont care. I just need to get it working at least in FF.
So if I understand you correctly you drop some files and you want to populate a file input object
I see a drop example here http://help.dottoro.com/ljslrhdh.php
but to populate the file field you will need a pretty heavy privilege change using a signed script - UniversalFileRead is probably the one you need

Categories

Resources