I give user the option of uploading a file like this
<form action="#" onsubmit="return Checkfiles(this);">
<center><input type="file" id="filename">
<input type="submit" value="Go!"></center>
</form>
When user uploads the file, I validate the file using the following javascript function
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "pdf" )
{
return true;
}
else
{
alert("Upload pdf files only");
fup.focus();
return false;
}
}
</script>
Evertything is working fine with it.
But I want to validate file by some other means and not just by its extension
I will give reason for doing this. I renamed an image file to image.pdf and now its in pdf format but couldnt be opened.
So I want to validate a pdf file in exact way. Is there any other way to check other than by its extension?
Edit
I want to do validation at server end using jsp page. So what should I do for that?
Thanks in ADVANCE :)
To validate a filetype on javascript, here are some ways:
// Your way: getting the extension and checking it.
// I suggest this way instead of using indexOf:
var ext = fileName.split('.').reverse()[0]
// Splits by '.', reverse the array, and returns the first element
// Another way: checking the type of the file
if ( fup.files[0].type === 'application/pdf' ) {
console.log( 'It is validated!' )
}
Live example: http://jsbin.com/akati3/2 thanks to https://stackoverflow.com/a/4581316/851498
But then, you should really validate this on the server side as others said.
Any kind of javascript validation is only for users comfort. Everything should be validated on serverside too. User can easily disable or modify any javascript code.
Anyway. you can't check file contents in javascript.
In PHP, you can use http://www.php.net/manual/en/function.finfo-file.php to detect file type by it's contents. Most of other languages should have similar functionality.
As far as I know, checking if a pdf actually is a pdf can only be done on server side. You could try and open it with IText or something similar; I bet it throws some sort of exception when you try opening or modifying something else then a PDF.
Related
I am creating a web portal where end user will upload a csv file and I will do some manipulation on that file on the server side (python). There is some latency and lag on the server side so I dont want to send the message from server to client regarding the bad format of uploaded file. Is there any way to do heavy lifting on client side may be using js or jquery to check if the uploaded file is "comma" separated or not etc etc?
I know we can do "accept=.csv" in the html so that file extension has csv format but how to do with contents to be sure.
Accessing local files from Javascript is only possible by using the File API (https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) - by using this you might be able to check the content whether it matches your expectations or not.
Here's some bits of code I used to display a preview image clientside when a file is selected. You should be able to use this as a starting point to do something else with the file data. Determining whether its csv is up to you.
Obvious caveat:
You still have to check server side. Anyone can modify your clientside javascript to pretend a bad file is good.
Another caveat:
I'm pretty sure that you can have escaped comma characters in a valid csv file. I think the escape character might be different across some implementations too...
// Fired when the user chooses a file in the OS dialog box
// They will have clicked <input id="fileId" type="file">
document.getElementById('fileId').onchange = function (evt) {
if(!evt.target.files || evt.target.files.length === 0){
console.log('No files selected');
return;
}
var uploadTitle = evt2.target.files[0].name;
var uploadSize = evt2.target.files[0].size;
var uploadType = evt2.target.files[0].type;
// To manipulate the file you set a callback for the whole contents:
var FR = new FileReader();
// I've only used this readAsDataURL which will encode the file like data:image/gif;base64,R0lGODl...
// I'm sure there's a similar call for plaintext
FR.readAsDataURL($('#file')[0].files[0]);
FR.onload = function(evt2){
var evtData = {
filesEvent: evt,
}
var uploadData = evt2.result
console.log(uploadTitle, uploadSize, uploadType, uploadData);
}
}
Please I need help to edit a txt file in client side, I can't find a good method. I need update the data automatic, without confirmation, like it:
<button onclick="updatefile()">Update</button>
<script>
functiom updatefile(){
var file = "d:\test.txt"
var data = //here any function for load all data from file
...
...
data .= " new data to add";
//here any function for save data in test.txt
.....
}
</script>
Please help me.
You cannot do this in that manner using JS. What you CAN do though is to download it on the client, without having the server intervene by using data urls.
Setting the name of said downloaded file is not cross browser compatible unfortunately...
HTML
<textarea id="text" placeholder="Type something here and click save"></textarea>
<br>
<a id="save" href="">Save</a>
Javascript
// This defines the data type of our data. application/octet-stream
// makes the browser download the data. Other properties can be added
// while separated by semicolons. After the coma (,) follows the data
var prefix = 'data:application/octet-stream;charset=utf-8;base64,';
$('#text').on('keyup', function(){
if($(this).val()){
// Set the URL by appending the base64 form of your text. Keep newlines in mind
$('#save').attr('href', prefix + btoa($(this).val().replace(/\n/g, '\r\n')));
// For browsers that support it, you can even set the filename of the
// generated 'download'
$('#save').attr('download', 'text.txt');
}else{
$('#save').removeAttr('href');
$('#save').removeAttr('download');
}
});
Hopefully this is a pretty simple question for those who know javascript but I couldn't figure it out. Basically I have a save file dialog box created with this:
<div>
<input type="file" id="file" onchange="loadFile(this)">
</div>
It is linked to the "loadfile" function shown below:
function loadFile(input) {
var file = input.files[0]
var url = file.urn || file.name;
ID3.loadTags(url, function() {showTags(url);}, {tags: ["title","artist","album","picture"],dataReader: FileAPIReader(file)});
}
I am trying to replace the line
var file = input.files[0]
to be a file from a string (specified path) instead of relying on the file browser dialog. I have tried something like this:
var file = files("song.mp3")
but the resulting function will not work. I am guessing that my variable file isn't of the right type. How do I get it to be the same type as the selected file from the file dialog box?
Thanks in advance!
PS:
I am trying to link my script to a path on the server not the client.
If you want to access data from a website, then use the XMLHttpRequest object instead of the Files API.
On my page I have a bunch of file upload fields (all with name="files[]" so it can be processed as a PHP array).
They are all located in one of two divs, lets call them 'div1' and 'div2'.
How can I use javascript so that onSubmit, it checks the file types and all the files in div1 can only be 'pdf', and all the files in div2' can only be 'pdf' or 'doc'?
A simple alert popup box will do (ie. "Files can only be pdf")
Any suggestions?
****************UPDATE*******************
Made a more relevant question: Add a filetype validation to phpmailer?
You can make this:
HTML:
<form method="post" enctype="multipart/form-data" name="form">
<input type="file" name="file" /><br />
<input type="file" name="file" />
<input type="submit" />
</form>
JavaScript:
var fileInput = document.getElementsByName("file");
for(var i = 0, len = fileInput.length; i < len; i++) {
fileInput[i].addEventListener('change',
function(e) {
if(this.files[0].name.match(/\.pdf$/) == null) {
alert('Files can only be PDF.');
return;
}
},
false
);
}
File upload elements are heavily protected in browsers, and JS has minimal access to its contents. Anything dealing with the file itself is pretty much locked off, as any hole in the system could allow a malicious site to steal files from the user's computer.
The easiest workaround is to just put up a small note next to the fields say "PDF Only!" and then use a server-side script to confirm that it is a pdf.
You can address the form element and read the name attribute, then you get the file name and can work with the file extension.
But this may only be used to make it easier to the user - so you can detect wrong file types before the uploading process.
It is NOT a protection in any way.
You can also pass the filestypes expected to the dialog itself. Most file managers and browsers respect it and display only the files of the type you want to choose, but the user can click a dropdown and select "view all files" and pic whatever files he/she want.
This is done with the accept attribute.
If you want to help the user choosing the right file both methods above are appropriate and I would even use them together.
If you want to protect your service from wrong filetypes, you have to evaluate the files server side. A file extension checking is not appropriate, there are php functions available to determine the real mimetype of a file.
You can check on submit for each file upload using this code:
var parts = document.getElementById('myFileField').value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension. Needs to be PDF.');
}
Incorporating work by The Mask,
var fileInputs = document.getElementsByName("files[]");
for (var ele in fileInputs) {
if (ele.parentNode.id = 'div1') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF.');
}
}
else if (ele.parentNode.id = 'div2') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf' && parts[parts.length-1] != 'doc') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF or DOC.');
}
}
}
I want to restrict a file upload control to allow PDF files only. I want to use JavaScript for that.
I want to apply that JavaScript in file upload event.
You can check the file name on submit.
"hook to the <form>'s onsubmit with whatever method" {
filename = theFileElement.value;
if (!/\.pdf$/i.test(filename)) {
alert("error");
return false;
}
return true;
}
Note that this only checks if the file has an extension of .pdf. It does not (and cannot) check whether the file is really a just PDF or actually a nasty virus. Moreover, client side Javascript can easily be bypassed, so you should perform the check again on the server side.
var ext = fname.split(".");
var x=ext.length;
if(ext[x-1] == 'pdf'){
alert("Please upload doc file");
document.form.fname.focus();
return false;
}