How to get full path of user's file upload? - javascript

We have an issue tracking system on our intranet where we need to add effected files to the issue, including the path of the file.
We have been using an asp.net FileUpload control and using FileUpload1.PostedFile.FileName to get the path of the file that the user selects and uploads. The files are usually not on the users local machine, but on network drives that are on a separate server than the issue tracking system. We use the upload as an easy way to add files to the issue tracker.
This does not work in any recent browsers for security reasons, only on Internet Explorer which is on its way out.
Is there any way to get this to work? At least for intranet sites? Or is there a better way to go about this? We do absolutely need the file path, and if we had to copy and paste it would make this process take much longer as it would make it a two step process and many files often need to be added.
Here is a snippet of the asp.net page:
<asp:FileUpload ID="FileUpload1" runat="server" />
And here is how I was getting the file path:
Dim sFileLocation As String = ""
Dim sFileName As String = ""
Dim sExtension As String = ""
sFileName = GetFileName(Me.FileUpload1.FileName)
sExtension = GetExtension(Me.FileUpload1.FileName)
sFileLocation = Me.FileUpload1.PostedFile.FileName
sFileLocation = sFileLocation.Replace(sFileName, "")

This is only works for IE 11, did not test IE edge.
Chrome does not work.
Due to intranet, we only allow use IE internally.
Here is the logic I am using to check the file size and name, validateFile function can get the file path without problem
<asp:FileUpload ID="fuAFS" runat="server" CssClass="cssAFS cssFu" AllowMultiple="false" Width="550px" /> <asp:Button ID="btnAFS" runat="server" Text="Upload AFS" OnClientClick="return ValidateFile('cssAFS');" />
function ValidateFile(cssName) {
var fu = $('.' + cssName);
//Empty upload control file.length == 1
if (fu.length > 0) { //Upload control exists
var pathName = fu.val();
if (pathName == '') {
alert('Missing file. Please click the Browse button to select a file with extension pdf.');
return false;
}
}
return true;
}
$('.cssFu').on('change', function (e) {
var maxFileSize = $('#<%=hdnMaxFileSize.ClientID%>').val();
if (e.target.files.length == 1) {
if (e.target.files[0] != null) {
var size = e.target.files[0].size; //IE
var fileSize = e.target.files[0].fileSize; //Firefox
var pathName = $(this).val();
var ext = pathName.substring(pathName.lastIndexOf(".") + 1, pathName.length).toLowerCase();
if (size > maxFileSize * 1024 * 1024 || fileSize > maxFileSize * 1024 * 1024) {
alert('File size exceeds limit. Maximum file size permitted is ' + maxFileSize + ' MB.');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
} else if (ext != 'pdf') {
alert('Invalid File. Please upload a File with extension: PDF');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
}
var fileName = pathName.substring(pathName.lastIndexOf("\\") + 1, pathName.length);
if (fileName != '' && fileName.length > 100) {
alert('File name length over 100 characters, please rename the file and upload again.');
$(this).val('');
// Prevent form Upload
e.stopPropagation();
e.preventDefault();
}
}
}

#rgorr - FileUpload will never give you the full path for security reasons.
Server.MapPath(FileUpload1.FileName);

Related

Input File multiple Validation Javacript

It is possible to validate within a multiple Input file that one of the files is of type word (.doc, .docx) and another of type PDF (.pdf)?
I have a created a working codepen that shows you a javascript code which iterates over the files uploaded with the file upload input, and checks if their file extension is in pdf, doc or docx.
Though as others have mentioned in comments, checking file format in client-side is unsafe and you should double check on the server side.
Snippet below
function testFiles(){
var fileInput = document.getElementById('upload');
// iterate over files
for (let i = 0; i < fileInput.files.length; i++) {
var filename = fileInput.files[i].name
// get file extension
var file_extension = filename.split('.').pop()
if(file_extension == "pdf"
|| file_extension == "doc"
|| file_extension == "docx"){
alert(filename + ' is a .pdf, .doc or .docx file')
}
else alert(filename + ' is not an authorized file')
}
}
<input id="upload" type="file" onchange="testFiles()" multiple>

JavaScript: File Size Validation [duplicate]

Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
See following thread:
How to check file input size with jQuery?
<script type="text/javascript">
function AlertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size without using jQuery.
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);
This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Best solution working on all browsers ;)
function GetFileSize(fileid) {
try {
var fileSize = 0;
// for IE
if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
// before making an object of ActiveXObject,
// please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
// for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
alert("Uploaded File Size is" + fileSize + "MB");
}
catch (e) {
alert("Error is :" + e);
}
}
from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html
UPDATE :
We'll use this function to check if it's IE browser or not
function checkIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
// If Internet Explorer, return version number
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
} else {
// If another browser, return 0
alert('otherbrowser');
}
return false;
}
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Browsers with HTML5 support has files property for input type.
This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
var size = inpFiles.files.item(i).size;
alert("File Size : " + size);
}
Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.
If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).
function getFileSize(fileInputElement){
if (!fileInputElement.value ||
typeof fileInputElement.files === 'undefined' ||
typeof fileInputElement.files[0] === 'undefined' ||
typeof fileInputElement.files[0].size !== 'number'
) {
// File size is undefined.
return undefined;
}
return fileInputElement.files[0].size;
}
ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
try {
var fileSize = 0;
//for IE
if (navigator.userAgent.match(/msie/i)) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
return (fileSize < 2.0);
}
catch (e) {
alert("Error is :" + e);
}
}
you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
var req = $.ajax({
type: "HEAD",
url: yoururl,
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Get the size of the file by files.item(i).size.
You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/
You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.
In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.

Javascript uploading duplicates

I have a bit of html with an area where a user can drag and drop files to upload. Nested within, is a "browse for files" button that clicks() a hidden file input should they choose the traditional upload method. Everything works well thus far with the exception that if a user drags and drops multiple files (more than one), it uploads each of them twice (3 dropped files uploads 6 files). It does not do this if the user uploads via the browse for files button, so I've narrowed it down to my on ondrop function and included that below. I can post additional code if the problem isn't in this code block.
Update: I logged my variable droppedfile to the console once before the for loop and once after and noticed that when logged after the for loop and 2 files were dropped, the variable contained 2 fileLists and each list contained both of the files (making 4 uploads). How is my for loop altering my variable??
dropzone.ondrop = function(e){
e.preventDefault();
this.className = 'dropzone';
var droppedfile = e.target.files || e.dataTransfer.files;
for (i=0; i < droppedfile.length; i++) {
if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
alert(droppedfile[i].type + " file types are not allowed.");
}else{
uploadButton.innerHTML = 'Uploading...';
//calls a function that assigns the file to a new formdata obj and sends via ajax
upload(droppedfile);
}
}
}
The problem occurs because you are uploading both the files each time the for loop is executed.
Replace
upload(droppedfile);
witn
upload(droppedfile[i]);
Alternatively You can ensure all files are valid before uploading
var valid=true;
for (i=0; i < droppedfile.length; i++) {
if(droppedfile[i].type != "text/plain" && droppedfile[i].type != "application/pdf" && droppedfile[i].type != "application/msword"){
alert(droppedfile[i].type + " file types are not allowed.");
valid=false;
}
}
if(valid) {
uploadButton.innerHTML = 'Uploading...';
upload(droppedfile);
}

Reset fileupload control from javascript

I have a ASP website page where i have a upload control added
<asp:FileUpload ID="FileUpload1" runat="server"
BorderStyle="None" Width="215px" onchange="return checkfile();" style="margin-left: 14px" BackColor="#F0F0F0" />
From javascript i am validating the file which will be uploaded. If it is of type .exe then I will not allow to upload and give a message. if not i will display the file name in label "lblFileName" . But the problem if error(in case file is exe) then i want to reset the upload control(FileUpload1) . Now it will show only message but allows form to submit along with the .exe file.So how I can reset it?
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = "you cannot attach exe file";
return false;
}
else {
document.getElementById('<%=lblFileName.ClientID%>').innerHTML = filename;
}
}
Your code is the problem onchange="return checkfile();"
And your function should look like
function checkfile() {
var filename = document.getElementById("FileUpload1").value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
filename = filename.substring(lastIndex + 1);
}
var FileExt = filename.split('.').pop();
if (FileExt == "exe") {
document.getElementById('lblFileName').innerHTML = "you cannot attach exe file";
document.getElementById("FileUpload1").value='';
return false;
}
else {
document.getElementById('lblFileName').innerHTML = filename;
}
}
Return will disallow file to put in your file upload control so this will solve your problem
Please check demo here
I am doing it this way using jquery:
$(function () {
$('<%= fileUploadCV.ClientID %>').change(function () {
//because this is single file upload I use only first index
var f = this.files[0]
//here I check if the file size is bigger than 8 MB (numbers below are in bytes)
if (f.size > 8388608 || f.fileSize > 8388608)
{
//show an alert to the user
alert("Allowed file size exceeded. (Max. 8 MB)")
//and RESET file upload control
this.value = null;
}
})
});

Get file size before uploading

Is there any way to find out the file size before uploading the file using AJAX / PHP in change event of input file?
For the HTML bellow
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
See following thread:
How to check file input size with jQuery?
<script type="text/javascript">
function AlertFilesize(){
if(window.ActiveXObject){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.getElementById('fileInput').value;
var thefile = fso.getFile(filepath);
var sizeinbytes = thefile.size;
}else{
var sizeinbytes = document.getElementById('fileInput').files[0].size;
}
var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
fSize = sizeinbytes; i=0;while(fSize>900){fSize/=1024;i++;}
alert((Math.round(fSize*100)/100)+' '+fSExt[i]);
}
</script>
<input id="fileInput" type="file" onchange="AlertFilesize();" />
Work on IE and FF
Here's a simple example of getting the size of a file before uploading. It's using jQuery to detect whenever the contents are added or changed, but you can still get files[0].size without using jQuery.
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Here's a more complete example, some proof of concept code to Drag and Drop files into FormData and upload via POST to a server. It includes a simple check for file size.
I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);
This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Best solution working on all browsers ;)
function GetFileSize(fileid) {
try {
var fileSize = 0;
// for IE
if(checkIE()) { //we could use this $.browser.msie but since it's deprecated, we'll use this function
// before making an object of ActiveXObject,
// please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
// for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
alert("Uploaded File Size is" + fileSize + "MB");
}
catch (e) {
alert("Error is :" + e);
}
}
from http://www.dotnet-tricks.com/Tutorial/jquery/HHLN180712-Get-file-size-before-upload-using-jquery.html
UPDATE :
We'll use this function to check if it's IE browser or not
function checkIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)){
// If Internet Explorer, return version number
alert(parseInt(ua.substring(msie + 5, ua.indexOf(".", msie))));
} else {
// If another browser, return 0
alert('otherbrowser');
}
return false;
}
$(document).ready(function() {
$('#openFile').on('change', function(evt) {
console.log(this.files[0].size);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="upload.php" enctype="multipart/form-data" method="POST" id="uploadform">
<input id="openFile" name="img" type="file" />
</form>
Browsers with HTML5 support has files property for input type.
This will of course not work in older IE versions.
var inpFiles = document.getElementById('#fileID');
for (var i = 0; i < inpFiles.files.length; ++i) {
var size = inpFiles.files.item(i).size;
alert("File Size : " + size);
}
Please do not use ActiveX as chances are that it will display a scary warning message in Internet Explorer and scare your users away.
If anyone wants to implement this check, they should only rely on the FileList object available in modern browsers and rely on server side checks only for older browsers (progressive enhancement).
function getFileSize(fileInputElement){
if (!fileInputElement.value ||
typeof fileInputElement.files === 'undefined' ||
typeof fileInputElement.files[0] === 'undefined' ||
typeof fileInputElement.files[0].size !== 'number'
) {
// File size is undefined.
return undefined;
}
return fileInputElement.files[0].size;
}
ucefkh's solution worked best, but because $.browser was deprecated in jQuery 1.91, had to change to use navigator.userAgent:
function IsFileSizeOk(fileid) {
try {
var fileSize = 0;
//for IE
if (navigator.userAgent.match(/msie/i)) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in b
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //size in b
fileSize = fileSize / 1048576; //size in mb
}
return (fileSize < 2.0);
}
catch (e) {
alert("Error is :" + e);
}
}
you need to do an ajax HEAD request to get the filesize. with jquery it's something like this
var req = $.ajax({
type: "HEAD",
url: yoururl,
success: function () {
alert("Size is " + request.getResponseHeader("Content-Length"));
}
});
Get the size of the file by files.item(i).size.
You should try this.
https://www.geeksforgeeks.org/validation-of-file-size-while-uploading-using-javascript-jquery/
You can use PHP filesize function. During upload using ajax, please check the filesize first by making a request an ajax request to php script that checks the filesize and return the value.
You can by using HTML5 File API: http://www.html5rocks.com/en/tutorials/file/dndfiles/
However you should always have a fallback for PHP (or any other backend language you use) for older browsers.
Personally, I would say Web World's answer is the best today, given HTML standards. If you need to support IE < 10, you will need to use some form of ActiveX. I would avoid the recommendations that involve coding against Scripting.FileSystemObject, or instantiating ActiveX directly.
In this case, I have had success using 3rd party JS libraries such as plupload which can be configured to use HTML5 apis or Flash/Silverlight controls to backfill browsers that don't support those. Plupload has a client side API for checking file size that works in IE < 10.

Categories

Resources