Photoshop Script Renaming Files On Mac Not Working - javascript

I need to rename files using Photoshop Script and the code works fine on Windows but doesn't work on Macintosh. The code runs without error but the files name stays the same on Mac OS. It changes the file name on Windows.
Hostscript Code:
function RenameTest(){
var fpath = Folder.myDocuments + '/test.rtf';
var nfile = File(fpath);
var nfile_newname = Folder.myDocuments + '/test.ini';
nfile.rename(nfile_newname);
}
Main.js Code:
csInterface.evalScript('RenameTest()');
Thanks for any help!

I found the solution if anyone needs it.
This code works in Windows but not on Mac:
function RenameTest(){
var fpath = Folder.myDocuments + '/test.rtf';
var nfile = File(fpath);
var nfile_newname = Folder.myDocuments + '/test.ini';
nfile.rename(nfile_newname);
}
This works on both Windows and Mac:
function RenameTest(){
var fpath = Folder.myDocuments + '/test.rtf';
var nfile = File(fpath);
var nfile_newname = 'test.ini';
nfile.rename(nfile_newname);
}
The nfile.rename must only be the file name and extension. Don't add the path.

Related

Javascript redirect using windows.locaton.href OR windows.locaton.replace is not working. Error: window not defined

I have looked at all of the questions around windows.locaton.href and windows.locaton.replace not working, but still can't figure out why this redirect is not working in JavaScript. There are two JS functions I am calling when a button is clicked with submit.
<input type="submit"
onclick="NotifyUserOfNewBudgets('#Field1');redirect2MainLookup('#primaryFilename');"
class="SaveChangeButton" value="Create New Budget">
The two functions are defined in Javascript as:
<script>
function NotifyUserOfNewBudgets(val) {
alert("New Budget will be saved. NewVal=" + val);
var ireturn;
document.getElementById("NewBudgetID").value = val;
document.getElementById("formMode").value = "Update";
}
function redirect2MainLookup(primaryFilename) {
var loc = window.location.pathname;
var host = document.location.host;
var dir = loc.substring(0, loc.lastIndexOf('/'));
//Replace the word Edit with blank so this redirects correctly
var newdir = dir.replace("NewBudget", "");
var newpath = host + newdir + primaryFilename;
alert('newpath location = http://' + newpath);
try {
windows.locaton.href = "http://" + newpath;
//window.location.replace('http://' + newpath);
} catch (err) { alert("Error: " + err);}
}
</script>
The error I get in the try()catch() is windows is not defined and then is stays on the same page. I get the same error using windows.locaton.replace() too. I have lots of pages doing redirects, can't figure out why this one fails.
You have a number of spelling mistakes. window is the object you are looking to reference. location is the property you are looking to access. Right now, you are using windows.locaton. windows is not a thing, nor is locaton. Keep an eye on undefined errors, they can tell you a lot about the state of your code.

Display a waiting gif during a javascript function

I write a script to get a text file, to modify this texter file and then I import the file in our software.
The problem is that the import of the file is very slow (just this part of the script could take more than 1 minute sometime).
I would like to display a waiting gif during this process, so the user can see that the process is running, and he need to wait.
Some precision:
- It's only a javascript file with no html page
- The script is launched with a button in our software and I have access to ActiveXObject if necessary
Here is a sample code :
function importFec()
{
var iOpenDlg = 1;
var sPath = "Deskop";
var sTypes = "Fichier Texte (*.txt)|*.txt";
var sExt = "txt";
//Allow me to select a file in Windows
cheminFEC = fileDialog(iOpenDlg, sPath, sTypes, sExt);
var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1;
var f1 = fso.OpenTextFile(cheminFEC, ForReading);
var texte = f1.ReadAll();
var tableauFEC = [];
var tableauTest = [];
tableauFEC = texte.split(/\r\n/);
tableauTest = tableauFEC[0].split("\t");
var delimiter = "\t";
if (tableauTest.length == 1)
{
tableauTest = tableauFEC[0].split("|");
var delimiter = "|";
}
var nbColonne = tableauTest.length;
for (var i=0;i<tableauFEC.length;i++)
{
var tab = tableauFEC[i].split(delimiter);
tableauFEC[i] = new Array(25);
for (var j=0;j<nbColonne;j++)
{
tableauFEC[i][j] = tab[j];
}
}
//Make some change in the table to adapt my texte file
//Then create a new texte file C:\\FichierFEC\\FECModifie.txt
createNewFEC(tableauFEC);
var cwfConfiguration = Application.ApplicationInfo("ProgramPath")+"\\Library\\ImportFEC\\ImportFEC23032017.vgl"
var oImport = Import(ipASCII)
oImport.ImportComponents = CWImportComponents.icGeneralLedger
oImport.ASCIILayoutFile = cwfConfiguration
oImport.ASCIIDataFile = "C:\\FichierFEC\\FECModifie.txt"
//This is the function which take a long moment to execute
oImport.RunImport()
}
Thanks for your answer and explanation
I finnaly found another solution.
At the beggining of my script, I launch a .hta file with a GIF and a small texte.
At the end of my script, I close the .hta file
Thanks

How my HTML application treats relative addresses depends too much on how it is run

My HTML application file F:\relroot\libname.lib\textapp.hta (name altered) contains the following function:
function fullNameOfFile(filename) {
var fso = newMedium(); return fso.GetAbsolutePathName(filename)
}
When I run the application via Open or double-click it in the directory,
fullNameOfFile("../etc.txt") returns "F:\relroot\etc.txt" [runs perfectly!].
When I run it via Open with:Microsoft HTML Apln Host, however:
fullNameOfFile("../etc.txt") returns "C:/Windows/etc.txt" [wrong number!].
How should I code to get to work regardless of how the application is run?
I think I might have "Aspie-rigged" a solution (or maybe two)
Apparently opening the HTML application via Open (or double-click) presets the "current" directory to the directory containing the app while opening via Open With:Microsoft® HTML Application Host uses a default directory (like «C:\WINDOWS\system32»)
var shell = new ActiveXObject("WScript.Shell");
var wasDir = shell.currentDirectory /* OPTIONAL: push original current directory
to allow restoration later */
var swDL = false; // for differences in device file format
var splitter = (swDL ? '/' : '\\') // foreslash v. backslash
var slashes = (swDL ? '///' : '//') /* slashes between scheme/protocol
and authentication/host */
var lhref = swDL ? unescape(location.href) : document.URL;
var newDir = lhref.slice(location.protocol.length + slashes.length,
lhref.lastIndexOf(splitter));
/*
// uncomment this block for an "inside window"
alert("Entering Directory: «" + wasDir + "»\n" +
"Protocol/Scheme: «" + location.protocol + "»\n" +
"Location HREF: «" + lhref + "»\n" +
"Trial Directory: «" + newDir + "»");
*/
shell.currentDirectory = newDir
It seems to work like a charm on my system (Dell PC, Internet Explorer/¿Edge). I threw in some comments as well in case the next user needs to tweak it for their system.

js:Window.open() for trying to open local folder failed

I can not open local file ,meanwhile i use "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --allow-file-access-from-files on my shortcut of my google chrome.
the explorer tips the security mode had been closed and I can open a new window using js or href attribute.
But the question is :why each time I click the href ,it always open a blank page and nothing to display.so..
function copyUrl(obj)
{
var href = $(obj).attr("hreff");
var hideInput = $("#hidInputHref");
hideInput.val(href);
hideInput.select();
try
{
document.execCommand('copy');
var opener = window.open('file:////C:/windows');
// opener.document.write("<iframe src='c:\' width='100%' height='100%'></iframe>");
//var test = "<body><script>" +
// "alert(1);console.log(1);"
//"<" + "\/script><div>11111111111</div></body>";
////var stateObj = { foo: "bar" };
//opener.document.write(test);
//opener.history.pushState("", "page 2", "./a.html");
//opener.location.href = "www.baidu.com";
//opener.location.reload();
opener.opener.location.href = "C:\windows";
}
catch (err)
{
console.log(err);
}
}
C# code:
partsQueryList[i].ImageRefLink = "<a onclick='copyUrl(this)' hreff='" + "C:\\" + "' ><font color='blue'>ImageRefLink</font></a>";
btw,when I tried to use pushSate method ,it can push a new url to new window,but It can not solve crossdomain issue.so...how could I solve it?thanks!
You have 4 slashes instead of 3. Try this :
var opener = window.open('file:///C:/windows');
Note: Also C:/windows doesn't seem like a valid file. Try with a valid file name.
Check this post for more help : Open a local HTML file using window.open in Chrome

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories