Custom the downloaded file name and prevent number adding in js - javascript

I have following simple code for downloading file.
let text = 'download'
function make(){
const data = new Blob([text],{ type: 'type: "text/plain"' })
document.querySelector('a').download = 'untitle'
document.querySelector('a').href = window.URL.createObjectURL(data);
}
make()
<a download>Download</a>
Broswer (in chrome not sure about other broswer) will automatically specify the number for the second or more time of downloading a same name file.
Example:
first time download: untitle.text
second time download: untitle(1).text
......
Is it possible to prevent the browswer of this behavior from happening ?
Thanks
You could try in https://jsfiddle.net/yapb2xus/1/

You just can't, that's the default behavior for most of the browsers and almost all OSes because you can't have two files with the same name.
Since chrome (and firefix I think) automatically save the file in a default path, in the first time the file untitle.text will not exist and will be saved with original name. At second tryz the file will exist on default download path, so the browser automatically add a sufix to it.
What you can try is to create your own sequence, adding a timestamp or something else to the name at every click on the link.

Related

Dynamic website with monitoring

I want to create a website which monitors a text file on the same domain, and updates a paragraph automatically when the text file changes. Any good ideas on what i can possibly use?
I feel like having a JavaScript file running a loop which monitors the file is not good practice, so any other suggestions would be great!
If you're doing it on the client, you can't automatically access the users file system. You need to open the file using dialog, select the file.
Once you have the file you can use the lastModified property of the file to check when it was modified. If you store the reference to that file you can then create an interval which will check every x if the file changed.
One global variable to keep track of most recent file modification date (so later we can compare if it's different)
var lastModificationDate = undefined;
Then when file is selected, you want to get the file and set the lastModificationDate property and start the interval.
file = input.files[0];
lastModificationDate = file.lastModified;
setInterval(checkFile, 500);
Your checkFile function would look like:
var file = input.files && input.files[0];
if (file && lastModificationDate && file.lastModified.getTime() != lastMod.getTime()) {
lastModificationDate = file.lastModified;
// Do something else, file was modified
}
The above functionality is achieved using HTML5 File API, you can read more about it here.
For a Node.js solution:
Use the fs.watchFile functionality built into the core of Nodes File System module.
fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
mtime is the modification time in the snippet above. This function would automatically fire on file change once implemented, unlike the solution above for client side.
You can read more about fs.watchFile here.

set file attribute filesystemobject javascript

I have created a file as part of a script on a network drive and i am trying to make it hidden so that if the script is run again it should be able to see the file and act on the information contained within it but i am having trouble doing this. what i have so far is:
function doesRegisterExist(oFs, Date, newFolder) {
dbEcho("doesRegisterExist() triggered");
sExpectedRegisterFile = newFolder+"\\Register.txt"
if(oFs.FileExists(sExpectedRegisterFile)==false){
newFile = oFs.OpenTextFile(sExpectedRegisterFile,8,true)
newFile.close()
newReg = oFs.GetFile(sExpectedRegisterFile)
dbEcho(newReg.Attributes)
newReg.Attributes = newReg.Attributes+2
}
}
Windows Script Host does not actually produce an error here and the script runs throgh to competion. the only guides i have found online i have been attempting to translate from VBscript with limited success.
variables passed to this function are roughly declared as such
var oFs = new ActiveXObject("Scripting.FileSystemObject")
var Date = "29-12-2017"
var newFolder = "\\\\File-Server\\path\\to\\folder"
I know ActiveX is a dirty word to a lot of people and i should be shot for even thinking about using it but it really is a perfect fit for what i am trying to do.
Please help.
sExpectedRegisterFolder resolves to \\\\File-Server\\path\\to\\folder\\Register which is a folder and not a file.
I get an Error: file not found when I wrap the code into a try/catch block.
I tested the code on a text file as well, and there it works.
So you're either using the wrong method if you want to set the folder to hidden.
Or you forgot to include the path to the text if you want to change a file to hidden.
( Edit: Or if Register is the name of the file, add the filetype .txt ? )
If you change GetFile to GetFolder as described in https://msdn.microsoft.com/en-us/library/6tkce7xa(v=vs.84).aspx
the folder will get hidden correctly.

Adobe Reader Javascript Open .DOC

I just tried to many code from internet to open automatically .doc which are attached in PDF but i get this : "Cannot open type of application/msword"
I tried this:
var oDoc = openDataObject("image.doc"); console.println(oDoc.path);
I tried to find another function which are specify the type of the document and to can open it in Microsoft Word!
Regards
The openDataObject method will throw an exception instead of returning a Doc if any of the following conditions are true:
The document that this method is being called for does not contain the requested embedded data object.
The data object is not a PDF document.
Permissions forbid opening attachments by means of JavaScript.
Instead of openDataObject which tells the viewer to open the file, use exportDataObject with the launch parameter. 0 will prompt the user to save the file, 1 will save the file and launch it.
this.exportDataObject({ cName: "image.doc", nLaunch: 1 });

How to use SaveAs function in Adobe Acrobat

I was trying to implement a javascript into a pdf button.Once you click it, it will allow you to .
I know there are security issues which does not allow you to use this function in pdf. And it requires you to put a SaveAs Javascript to make it trusted Functions in the computer. So i have put following code as a trusted function in my computer.
var mySaveAs = app.trustedFunction(
function(oDoc,cPath,cFlName)
{
// Ensure path has trailing "/"
cPath = cPath.replace(/([^/])$/, "$1/");
try{
oDoc.saveAs(cPath + cFlName);
}catch(e){
app.alert("Error During Save");
}
}
);
And i have these codes in my pdf file's button which allows me to saveas another pdf file which name is "123.pdf".
var doc = app.activeDocs;
var aMyPath = this.path.split("/");
aMyPath.pop();
var pathname = aMyPath.join("/")
if(typeof(mySaveAs) == "function"){
mySaveAs(doc,pathname,"345.pdf")
}else{
app.alert("Missing Save Fucntion" + "Please contact forms administrator");
}
i don't know why, but it still gives me an error message saying "Error During Save". Does anyone know the reason? Or there's a easier way to use the SaveAs function using JavaScript in Acrobat. Thanks in advance.
app.activeDocs is an array of Doc objects. Therefore the variable doc (which has not the smartest name, BTW) is an array.
However the save function requires one Doc object to work.
Try whether replacing
mySaveAs(doc,pathname,"345.pdf")
with
mySaveAs(this,pathname,"345.pdf")
would work.
I've an old code for similar thing, and that used the below code for saving the current file in new folder. I had used this in Adobe 6. Check if this works for you.
this.saveAs(destfolder+filename);

Create file to download js

I'm receiving a JSON output from an API, and i want to use it with JS and also save that output to file. Is there any way to trigger the browser download machanism using JS with thet output?
Maybe now some browsers support the attribute download but you don't trigger the browser to automatically download the file.
the only way i know is #BAS's solution but without a filename.
tested in chrome ..
array=[{a:'1',b:'2'},{x:'3',y:'4'}];
function dl(array,filename){
var b=document.createElement('a');
b.download=filename;
b.textContent=filename;
b.href='data:application/json;base64,'+
window.btoa(unescape(encodeURIComponent(JSON.stringify(array))))
// or
// b.href='data:application/javascript;charset=utf-8,'+JSON.stringify(json);
return b
}
document.body.appendChild(dl(array,'my.json'));
example
http://jsfiddle.net/8yQcW/
UPDATE direct download works ... on chrome i tested.
on append simulate click
var e=document.createEvent('Events');
e.initEvent('click',true,false);
document.getElementById('dl').dispatchEvent(e);
http://jsfiddle.net/8yQcW/1/
You could try it with a data URI:
function triggerDownload(json) {
var dataUri = 'data:text;charset=utf-8,' + json;
window.open(dataUri);
}
Try entering data:text;charset=utf-8,{"Key":"Value"} into your browsers address bar. It should show you the save dialog.
See here for more information and browser support.

Categories

Resources