ASP.NET - Validate Excel File Content - javascript

I have a page with a file input where the user is supposed to upload an excel file to insert a large amount of records to a specific table. I found this Javascript code to help validate if the inserted file has one of the requested Excel extensions:
var hash = {
'xls': 1,
'xlsx': 1,
};
function checkExtension() {
var filename = $("#uploadFile").val();
var re = /\..+$/;
var ext = filename.slice(filename.lastIndexOf(".") + 1).toLowerCase();
if (hash[ext]) {
return true;
} else {
alert("Invalid file type. Please insert a valid Excel file.");
event.preventDefault();
return false;
}
}
However, as efficient as this code is at validating the file's extension, it won't validate the file's content allowing someone to upload a file with different type of content but it's extension renamed to ".xls" or ".xlsx". How can i get around this scenario?

You can Properly Validate Your Excel File in 3 steps
In Asp.net FileUploader Control has an Attribute Called 'accept' <asp:FileUploader accept='.xls,.xlsx'/>. It will by default let the user to select only xls and xlsx extension file. However still user can choose All file options to upload another file.
Verify if the Extension of the Filename contains .xls from Javascript as well as Code Behind.
Use Aspose.Cells dll and try to fetch the xls file it will return Exception 'InvalidFileFormatException' if the File is not xls or xlsx.

Related

<a> element does not recognize the file extension automatically when downloading a file

I'm currently developing an application where the user clicks on an element, that element calls a JS function and the function handles a file download.
The files are reports generated dynamically by Devexpress XtraReports module, converted to Base64 and then sent back to the client side. When the client receives the Base64 string, the JS function creates an <a> element, sets the href attribute to data:application/pdf;base64,JVBERi0xLjQNCiWio[...] and simulates a click with the click() event.
Here's the piece of JS code that handles the file download:
let downloadLink;
try {
downloadLink = executionId ? await getLinkPdfBase64(executionId) : false;
} catch (error) {
downloadLink = false;
console.log(error);
}
if (downloadLink) {
const aElement = document.createElement("a");
downloadLink = "data:application/pdf;base64," + downloadLink;
aElement.setAttribute("download", currentReportData.LayoutName);
aElement.setAttribute("href", downloadLink);
aElement.click();
aElement.remove();
} else {
DevExpress.ui.dialog.alert( //Ignore this, it's a Devexpress component
"Your report could not be generated",
"Alert"
);
}
The problem is:
When I generate a report with custom parameter types, Devexpress generates it correctly (the Base64, if converted to string, is visibly correctly formed) but the browser (Google Chrome) downloads the file with the extension ".0".
If the report has normal Devexpress parameters (like Strings, Int32, Guids, etc)) the file is downloaded with the correct ".pdf" extension.
Here's a picture of a correctly downloaded PDF and a ".0" extension file:
Could it be the JS function the cause or the solution to the problem? If not, almost for sure there will be something wrong with the report generator (Devexpress).
NB: If I manually change the ".0" extension to ".pdf" the file opens and it is displayed / formed correctly.
Turns out I ended up solving it just by adding the file extension ".pdf" in the download attribute, so when the browser can't recognize it, you are already specifying which one it is:
aElement.setAttribute("download", currentReportData.LayoutName + ".pdf");

How to get the file type of a CSV in jQuery

This is the input tag that I am using to select a file,
<input id="imprtUpldFileInpt" name="file" type="file"/>
And this is how I process the file details with jQuery,
var file = $("#imprtUpldFileInpt")[0].files[0];
var f_name = file.name;
var f_size = file.size;
var f_type = file.type;
var fileMimeTypeArr = ["text/comma-separated-values", "text/csv", "application/csv", "application/vnd.ms-excel"];
var fileTypePos = $.inArray(f_type, fileMimeTypeArr);
I am checking whether the selected file is a csv or not with the value of fileTypePos. If the value is greater than or equal to 0, then I conform that it is a csv file. But I am facing a problem in getting the file type.
If a csv is selected, the file name and size are obtained correctly. But I am not getting the file type.
The following screenshot shows the file details of a csv file,
I have added the possible mime types in fileMimeTypeArr for checking whether the file is a csv file or not. The problem is with getting the file type.
This problem does not occur if the csv file is saved in a machine that has MS Excel installed. But if a csv file is created/saved in a machine that does not have MS Excel, then this problem occurs.
Why the file type has ""?

How to upload a csv file multiple times on Safari using Angularjs?

I have written a web app where I want to upload a CSV file. It is working as intended on Chrome, but it does not work on Safari.
Below is the Angularjs code to upload file,
$scope.uploadFile = function (file) {
var name, extension, browser;
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
if (isSafari) {
name = file.fileName;
extension = name.split('.')[name.split('.').length - 1].toLowerCase();
if (extension != "csv") {
alert("Selected File is not a valid .CSV file. Please select a .CSV file.");
return false;
}
}
//Code to save file to server
}
Below is the HTML code to call the above function,
<input id="uploader" type="file" ngf-select="uploadFile(uploadedFile)"
ng-model="uploadedFile" ngf-max-size="100MB" name="file"
ngf-accept="'application/csv, text/csv, text/comma-separated-values, *.csv, .csv, application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/vnd.ms-excel'">
When I click the input button the first time, the function gets called correctly. The selected file gets uploaded as expected. The issue begins when I try to upload the same file the second time. The uploadFile function gets called as soon as I click the <input > file picker.
The above problem described occurs only in Safari, and not in Chrome.
How do I modify my code such a way that every time I click to upload a file, the function gets called only after I select the file?
Thank you for reading my question.

select a file without browsing using javascript

My main program prompts the user to browse for a file in order to convert it using ffmpeg. This is the format of the file browsing:
<div>
<p class="lead">1. Select audio file for conversion ( mp3, wma):</p>
<div class="quick-center">
<div class="quick-drop-outer quick-left"><input id="inFile" type="file" id="inputFile"/></div>
</div>
</div>
and this is the code where to launch the file and convert it according to selection: not whole code supported because no need of file conversion:
document.getElementById('inFile').addEventListener('change', handleFileSelect, false);
function readInputFile(file) {
// disable conversion for the time of file loading
$('#convert').attr('disabled', 'true');
// load file content
var reader = new FileReader();
reader.onload = function(e) {
$('#convert').removeAttr('disabled');
fileName = file.name;
fileBuffer = e.target.result;
}
reader.readAsArrayBuffer(file);
}
function handleFileSelect(event) {
var files = event.target.files; // FileList object
// files is a FileList of File objects. display first file name
file = files[0];
console.log(file);
if (file) {
$("#drop").text("Drop file here");
readInputFile(file);
}
}
now, here is my problem, what I want to do is to upload the file directly from a selected folder (upload) where the audio files are already there. I want instead of browsing for the file, I want the last file in the upload folder to be uploaded instead of "inFile" so that conversion can happen.
how could that happen.
edit: A small brief about my project. the user records his voice using HTML5 and the link of that audio is uploaded using ajax and php into a folder named upload.what I simply want is instead of browsing that file, I want to write down the path of the file in the selected folder automatically once recording is done for conversion.so, instead of dropping the file by user, the file would be dropped and conversion starts from there.
help please.Thank you in advance
From JavaScript You dont have access to files and directories on host system.
Why?
Because is VERY IMPORTANT SECURITY feature to block reading Your disc for files from scripts.

File upload validation by JavaScript

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;
}

Categories