I need to check if a file is a xls. I am trying this code, but I upload a xls file and I am getting the error Invalid file.
var acceptFileTypes = /(.|\/)(application\/vnd.ms-excel)$/i;
console.log(data.originalFiles[0]['type']); //application/vnd.ms-excel
if (!acceptFileTypes.test(data.originalFiles[0]['type'])) {
uploadErrors.push('Invalid file');
}
There is something wrong with the regex?
Here's your error: (.|\/)
This part needs to consume one character - it is actually equivalent to ..
Remove that part and you'll be fine. You also need to escape the periods:
var acceptFileTypes = /application\/vnd\.ms-excel$/i;
Of course, this is equivalent to:
var acceptFileTypes = "application/vnd.ms-excel";
var isExcel = yourFile.toLowerCase().indexOf(acceptFileTypes, yourFile.length - acceptFileTypes.length) == 0;
Related
I need to convert a path this UNC. I have searched and search and cannot piece anything together.
"\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
I need to remove the "\NAS_01\GlobalShare\Docs\Customers\" portion of the path and also "photo1.jpg" and end up with:
2017\S\Smith, John\
so that I can pass it to the following function:
function getDriveFolderNoCreate(path, rootFolder) {
var name, folder, search, fullpath;
// Remove extra slashes and trim the path
fullpath = path.replace(/^\/*|\/*$/g, '').replace(/^\s*|\s*$/g, '').split("/");
// Always start with the main Drive folder
folder = rootFolder;
for (var subfolder in fullpath) {
name = fullpath[subfolder];
search = folder.getFoldersByName(name);
if (search.hasNext()) {
var folder = search.next;
var folderID = folder.getId();
return folderID;
}
}
}
My intention is to return a url to open the Google Drive folder with the same path.
I ended up with a multi-part solution that works very well.
I paste the fill UNC path to cell B2.
This formula is in B3 =Index(split(B2, "\"), 0, 8)
It returns the exact folder name i need.
Then in my gs file:
function findDriveFolder() {
var pFId = "XYZ1233333333333";
var input = SpreadsheetApp.getActive().getRange("B3").getValue();
var folders = DriveApp.getFoldersByName(input);
Logger.log("folders: " + folders[0]);
while (folders.hasNext()) {
var folder = folders.next();
var url = folder.getUrl();
showAnchor("View Folder", url);
}
}
function showAnchor(name,url) {
var html = '<html><body>'+name+'</body></html>';
var ui = HtmlService.createHtmlOutput(html)
SpreadsheetApp.getUi().showModelessDialog(ui,"Files Folder");
}
I have not implemented the searchFolders part yet that I hope will speed it up. At least it's working for now.
Apps Script needs your input backslashes to be escaped if you are writing the string yourself (i.e. testing input).
wrong:
input = "\\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg"
right:
input = "\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photos1.jpg"
In Apps Script then, I am able to get the matching portion with the following regex:
/\d{4}\\[A-Z]\\.+\\/
i.e:
function unc2uri(input) {
const forwardSlash = String.fromCharCode(47);
const backSlash = String.fromCharCode(92);
if(!input)
input = '\\\\NAS_01\\GlobalShare\\Docs\\Customers\\2017\\S\\Smith, John\\photo1.jpg';
// Should show \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg
Logger.log(input);
const matcher = /\d{4}\\[A-Z]\\.+\\/;
const arrayOfMatches = input.match(matcher);
// Should show [2017\S\Smith, John\].
Logger.log(arrayOfMatches);
}
To verify, ask for the input string from someplace else (example, Browser.inputBox) and pass that to the above as input:
function readInput() {
unc2uri(Browser.inputBox("What's the path?"));
}
In the inputBox, you would enter the string you expect to be sent, as we view it, i.e. \\NAS_01\GlobalShare\Docs\Customers\2017\S\Smith, John\photo1.jpg
I have one doubt because I need to read a local file and I have been studying some threads, and I have seen various ways to handle it, in most of the cases there is an input file.
I would need to load it directly through code.
I have studied this thread:
How to read a local text file?
And I could read it.
The surprising part was when I tried to split the lines and words, it showed: � replacing accent letters.
The code I have right now is:
myFileReader.js
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
console.log('The complete text is', allText);
let lineArr = intoLines(allText);
let firstLineWords = intoWords(lineArr[0]);
let secondLineWords = intoWords(lineArr[1]);
console.log('Our first line is: ', lineArr[0]);
let atlas = {};
for (let i = 0; i < firstLineWords.length; i++) {
console.log(`Our ${i} word in the first line is : ${firstLineWords[i]}`);
console.log(`Our ${i} word in the SECOND line is : ${secondLineWords[i]}`);
atlas[firstLineWords[i]] = secondLineWords[i];
}
console.log('The atlas is: ', atlas);
let atlasJson = JSON.stringify(atlas);
console.log('Atlas as json is: ', atlasJson);
download(atlasJson, 'atlasJson.txt', 'text/plain');
}
}
};
rawFile.send(null);
}
function download(text, name, type) {
var a = document.getElementById("a");
var file = new Blob([text], {type: type});
a.href = URL.createObjectURL(file);
a.download = name;
}
function intoLines(text) {
// splitting all text data into array "\n" is splitting data from each new line
//and saving each new line as each element*
var lineArr = text.split('\n');
//just to check if it works output lineArr[index] as below
return lineArr;
}
function intoWords(lines) {
var wordsArr = lines.split('" "');
return wordsArr;
}
The doubt is: how could we handle those special character which are the vowels with accent?
I ask this, because even in the IDE thet interrogation marks appeared if we load the txt in UTF-8, so then I changed to ISO-8859-1 and it loaded well.
Also I have studied:
Read UTF-8 special chars from external file using Javascript
Convert special characters to HTML in Javascript
Reading a local text file from a local javascript file?
In addition, could you explain if there is a shorter way to load files in client javascript. For example in Java there is the FileReader / FileWriter / BufferedWriter. Is theren in Javascript something similar?
Thank you for you help!
It sounds like the file is encoded with ISO-8859-1 (or possibly the very-similar Windows-1252).
There's no BOM or equivalent for those encodings.
The only solutions I can see are:
Use a (local) server and have it return the HTTP Content-Type header with the encoding identified as a charset, e.g. Content-Type: text/plain; encoding=ISO-8859-1
Use UTF-8 instead (e.g., open the file in an editor as ISO-8859-1, then save it as UTF-8 instead), as that's the default encoding for XHR response bodies.
Put your text in an .html file with the corresponding content type,
for example:
<meta http-equiv="Content-Type" content="text/html; charset="UTF-8">
enclose the text between two tags ("####" in my example) (or put in a div)
Read the html page, extract the content and select the text:
window.open(url); //..
var content = newWindow.document.body.innerHTML;
var strSep="####";
var x = content.indexOf(strSep);
x=x+strSep.length;
var y = content.lastIndexOf(strSep);
var points=content.slice(x, y);
Is it possible to get the filename without the extension from the src filepath.
As an example, let's say the src file is my-file.png - located at images/my-file.png.
In my task I have this at the moment:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
When I reference filename for output it returns:
images/my-file.png
I want to only return the actual filename, without the path and without the extension:
my-file.png
How can I achieve this?
Might be pretty old but if someone else finds this SO., in reply for #user3143218 's comment :
slice(0, -4) will remove the last 4 characters from the name, so for the example my-file.png we will get my-file but for script.js we will get scrip. I suggest using a regex removing everything from the last dot.
You could use a regex like this:
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.substr(0, theFile.lastIndexOf('.')) || theFile;
That should give you my-file. The regex gives you the string after the last forward slash, and the next line removes everything after the last dot (and the dot).
Thanks to Andeersg's answer below I was able to pull this off. It might not be the best solution but it works. Final code is:
var processName = options.processName || function (name) { return name; };
var filename = processName(filepath);
var theFile = filename.match(/\/([^/]*)$/)[1];
var onlyName = theFile.slice(0, -4);
Now onlyName will return:
my-file
I have an input of type file, my question is: after I select the file, can the file name be limited to a certain number of characters ?
You can get the file name using
var filename = document.getElementById('file-id').value;
filename = filename.replace(/^.*[\\\/]/, '');
But limitation in sense, after uploading the file you can get the file name using above approach.
Then you can have
if (filename.length < 100 ) {
//do something
}
FYI: Evert thing happens only after the file being uploaded in client side. There is no use in limiting the filepath before uploaded to server.
Do you mean like this?
var limit = 8;
var fileName = document.getElementById("file-name-field").value();
// get both parts
var fileNameExtension = "." + fileName.split(".").pop();
var fileNameBase = fileName.substring(0, fileName.length()-fileNameExtension.length());
if(fileNameBase.length()>limit){
// now limit it and set it as fileName
fileName = fileNameBase.substring(0, limit) + fileNameExtension;
}
Most browsers don't allow modification of the value attribute of file fields. It's a security hole, because it would allow a malicious page to retrieve an arbitrary file using a hidden field.
Please try following JavaScript to check length of the file name.
function valueCheck()
{
var filePath = document.getElementById("file").value;
var fileName = filePath.replace(/[^\\\/]+$/, "");
if(fileName !=null && fileName.length >10)
{
alert('Filename if bigger');
}
}
Demo URL : http://jsfiddle.net/BhaveshKachhadiya/6EPvg/6/
I am using the following function to save text to a file (on IE-8 w/ActiveX).
function saveFile(strFullPath, strContent)
{
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
var flOutput = fso.CreateTextFile( strFullPath, true ); //true for overwrite
flOutput.Write( strContent );
flOutput.Close();
}
The code works fine if the text is fully Latin-9 but when the text contains even a single UTF-8 encoded character, the write fails.
The ActiveX FileSystemObject does not support UTF-8, it seems. I tried UTF-16 encoding the text first but the result was garbled. What is a workaround?
Try this:
function saveFile(strFullPath, strContent) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var utf8Enc = new ActiveXObject("Utf8Lib.Utf8Enc");
var flOutput = fso.CreateTextFile(strFullPath, true); //true for overwrite
flOutput.BinaryWrite(utf8Enc.UnicodeToUtf8(strContent));
flOutput.Close();
}
The CreateTextFile method has a third parameter which decides whether file be written unicode or not. You can do like:
var flOutput = fso.CreateTextFile(strFullPath,true, true);
Interestingly, way back I had created this little script to save files in unicode format:
Set FSO=CreateObject("Scripting.FileSystemObject")
Value = InputBox ("Enter the path of the file you want to save in Unicode format.")
If Len(Trim(Value)) > 0 Then
If FSO.FileExists(Value) Then
Set iFile = FSO.OpenTextFile (Value)
Data = iFile.ReadAll
iFile.Close
Set oFile = FSO.CreateTextFile (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),True,True)
oFile.Write Data
oFile.Close
If FSO.FileExists (FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value)) Then
MsgBox "File successfully saved to:" & vbCrLf & vbCrLf & FSO.GetParentFolderName(Value) & "\Unicode" & GetExtention(Value),vbInformation
Else
MsgBox "Unknown error was encountered!",vbCritical
End If
Else
MsgBox "Make sure that you have entered the correct file path.",vbExclamation
End If
End If
Set iFile = Nothing
Set oFile= Nothing
Set FSO= Nothing
Function GetExtention (Path)
GetExtention = Right(Path,4)
End Function
Note: This is VBScript code, you should save that code in a file like unicode.vbs, and once you double click that file, it will run.
Add a third parameter, true, in your call to the CreateTextFile method. See this page.
function saveFile(strFullPath, strContent) {
var fso = new ActiveXObject( "Scripting.FileSystemObject" );
var flOutput = fso.CreateTextFile( strFullPath, true, true ); //true for overwrite // true for unicode
flOutput.Write( strContent );
flOutput.Close();
}
object.CreateTextFile(filename[, overwrite[, unicode]])