JavaScript - Changing Save As Filename
Hello. I am new to the forums (I just started my Javascript journey last week), and was hoping to get help with something. I am currently developing a page which allows access to music on a server. This music is being streamed, but users are also able to download this music (assuming they have the license to do so). All of the music uploaded is of the .mp3 format, however they have no filetype extensions, and were not named using any particular naming convention. Because of this, I was hoping to change the filename (when a downloaded is initiated) to variables I have stored based on the current song.
I am currently simply opening a new page, in Chrome is looks like this: Code: chrome.tabs.create({ "url": song.url }) Hit presents the user with a prompt to save the file, however, its default name is a random alphanumeric string with no extension, as per their file name on my server. Is there an easy way to do this without renaming all the music server side? I do have the variables song.title and song.artist setup! All help is appreciated! Edit: Since this page is only for Chrome users, I listed the code I am using. I understand window.open and was originally using this. It functions the same, and if I need to revert back to using is instead, I shall. Similar TutorialsHi all, I have a webform that creates a word document as it's ouput (yes I know it only works on IE). Code: function createWordDoc(){ Doctxt = "some text here" var w=new ActiveXObject("Word.Application"); w.Visible=true; w.Documents.Add(); w.Selection.Font.Name="Times New Roman"; w.Selection.ParagraphFormat.Alignment = 1; w.Selection.TypeText(Doctxt); w.Documents.Save(); } My issue is with saving the file. At the moment, in the above code, it opens the save dialogue box, and populates the filename field with the first line of text in the document. What I want to be able to do is populate the filename field with a variable filename created by the function. Anyone know how to do this? I've tried the snippet below, which works with the dynamic filename, but it autosaves the file to "My Documents" folder without prompting. I need to be able to allow the location to be changed. Code: var FileName = "Myfile.doc" w.ActiveDocument.SaveAs(FileName); Any ideas? I'm trying to figure out a way to pass the filename before submission... I think I have to make an onChange command on the file field, but not sure how... This is what I have done so far: Code: <script type="text/javascript"> function theimage(){ var imgURL = document.getElementById('myfile').value; ste.execCommand("insertimage", imgURL); } </script> <input name="myfile" type="file" size="30" onchange="theimage();"> I'm trying to pass the value to theimage as sson the filename changes, but I'm doing something wrong... Any help is apreciated... I'm working on an internal website at work and employees have a cookie created when they login to the customer support tool. The filename is cookie:username@domain.com/ and I'd like to use javascript to pull a variable for their username to plug into a URL for a unique link when they're viewing one of our intranet pages. I'm a Javascript newbie so any help is appreciated. @domain.com/ will always be the same but I don't know how to pull the unique username from the filename of the cookie. I don't need to actually read the cookie. Thanks! Hello all, I have in my application input type file for uploading files. How can i do javascript validation to check if filename has special characters in it?? Thanks Hi I am trying to load html stream directly into webbrowser in delphi. The html contains java script. It loads xml and xsl files and display the xml content in the web browser. I got an error, says access denied for the command xmlDoc.load(fname); If I save the html into a file, test.html, and double click it, it is fine, no problem. The code is actually copied from w3schools.com. the html code as followed: <html> <head> <script> function loadXMLDoc(fname){var xmlDoc; if (window.ActiveXObject) { xmlDoc=new ActiveXObject("Microsoft.XMLDOM"); } else { alert('Your browser cannot handle this script'); } xmlDoc.async=false; xmlDoc.load(fname); return(xmlDoc); } function displayResult() { xml=loadXMLDoc("catalog.xml"); xsl=loadXMLDoc("catalog.xsl"); if (window.ActiveXObject) { ex=xml.transformNode(xsl); document.getElementById("example").innerHTML=ex; } } </script> </head> <body id="example" onLoad="displayResult()"> </body> </html> The delphi code is procedure TForm1.WBLoadHTML(WebBrowser: TWebBrowser; HTMLCode: string) ; var v: OleVariant; HTMLDocument: IHTMLDocument2; begin memo1.Lines.LoadFromFile('d:\test\htmltxtold.html'); HTMLCode := memo1.Text; WebBrowser1.Navigate('about:blank') ; HTMLDocument := WebBrowser.Document as IHTMLDocument2; v := VarArrayCreate([0, 0], varVariant); v[0] := HTMLCode; HTMLDocument.Write(PSafeArray(TVarData(v).VArray)); HTMLDocument.Close; end; Thanks a lot Hey, I'm trying to make a game, I learned how to do so by reading tutorials but the problem is that I do not know how to implement the save/load function into the game, the tutorial surrounding that area was very unclear to me, and here I am... Any tips on how to make this work is greatly appreciated, I wouldn't asked if I hadn't tried my best and every way I could think of. I'm still quite new to coding so... The first piece of code is the game, the second one is what I'm trying to make the game work with. I tried for a while and got the game to reset back to values, but only the values I set in the code so it never actually worked. The tutorial doesn't give any live examples and I really am... not that bright when it comes to coding Sorry and thanks, all inputs are appreciated. I read tutorial from links below, Javascript String Compression | Almost Idle Tutorial for save code Incremental Lesson 9 - For Loops | Almost Idle Tutorial for the game code Code: /*Pleae refer to Lesson 9.txt for a full description on this lesson*/ //The timer to run code every second var Timer = window.setInterval(function(){Tick()}, 1000); var buildings = []; //The object declaration for game saves function GameSave() { this.money = 0; this.buildings = []; for (var i = 0;i < buildings.length;i++) { this.buildings[i] = 0; } } //The object declaration for buildings function Building() { this.Name = "Lemonade Stand"; this.Cost = 10; this.PerSec = 1; } //The function to initialise all buildings function InitBuildings() { LoadBuilding("Lemonade Stand",10,1); } //The function to automatically load a building into the buildings array function LoadBuilding(name,cost,persec) { var cur = buildings.length; buildings[cur] = new Building(); buildings[cur].Name = name; buildings[cur].Cost = cost; buildings[cur].PerSec = persec; } //The function used to gather money function GatherMoney() { game.money++; //++ tells javascript to add 1 to the variable //Display the player's current money document.getElementById("money").innerHTML = game.money; } //The function that gets run every second function Tick() { for (var i = 0;i < buildings.length;i++) { game.money += game.buildings[i] * buildings[i].PerSec; } document.getElementById("money").innerHTML = game.money; } //The function to buy a lemonade stand function Build(id) { if (game.money >= buildings[id].Cost) { //Check if the player has enough money, then subtract it and add a new building if they do game.money -= buildings[id].Cost; game.buildings[id] = game.buildings[id] + 1; document.getElementById("money").innerHTML = game.money; document.getElementById("Building1Qty").innerHTML = game.buildings[id]; } } //Run this code once the page has loaded fully window.onload = function() { InitBuildings(); window.game = new GameSave(); }; Code: /*Pleae refer to Compression.txt for a full description on this lesson*/ function NewGame() { this.name = "Our Game"; this.description = "Our Game's Description"; this.numbers = []; for (var i=0;i<10;i++) { this.numbers[i] = i; } } var Game = new NewGame(); window.onload = function() { var SaveGame = JSON.stringify(Game); SaveGame = encode_utf8(SaveGame); SaveGame = lzw_encode(SaveGame); window.localStorage['SaveName'] = SaveGame; SaveGame = window.localStorage['SaveName']; SaveGame = lzw_decode(SaveGame); SaveGame = decode_utf8(SaveGame); window.GameTwo = JSON.parse(SaveGame); document.getElementById("name").innerHTML = "Name: " + GameTwo.name; document.getElementById("desc").innerHTML = "Description: " + GameTwo.description; var numbers = ""; for (var i=0;i<10;i++) { if (numbers.length == 0) {numbers = i;} else {numbers += ", " + i;} } document.getElementById("numbers").innerHTML = "Numbers: " + numbers; } // LZW-compress a string function lzw_encode(s) { var dict = {}; var data = (s + "").split(""); var out = []; var currChar; var phrase = data[0]; var code = 256; for (var i=1; i<data.length; i++) { currChar=data[i]; if (dict['_' + phrase + currChar] != null) { phrase += currChar; } else { out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); dict['_' + phrase + currChar] = code; code++; phrase=currChar; } } out.push(phrase.length > 1 ? dict['_'+phrase] : phrase.charCodeAt(0)); for (var i=0; i<out.length; i++) { out[i] = String.fromCharCode(out[i]); } return out.join(""); } // Decompress an LZW-encoded string function lzw_decode(s) { var dict = {}; var data = (s + "").split(""); var currChar = data[0]; var oldPhrase = currChar; var out = [currChar]; var code = 256; var phrase; for (var i=1; i<data.length; i++) { var currCode = data[i].charCodeAt(0); if (currCode < 256) { phrase = data[i]; } else { phrase = dict['_'+currCode] ? dict['_'+currCode] : (oldPhrase + currChar); } out.push(phrase); currChar = phrase.charAt(0); dict['_'+code] = oldPhrase + currChar; code++; oldPhrase = phrase; } return out.join(""); } function encode_utf8(s) { return unescape(encodeURIComponent(s)); } function decode_utf8(s) { return decodeURIComponent(escape(s)); } Reply With Quote 01-16-2015, 05:52 PM #2 Dormilich View Profile View Forum Posts Senior Coder Join Date Jan 2010 Location Behind the Wall Posts 3,532 Thanks 13 Thanked 372 Times in 368 Posts the problem is that I do not know how to implement the save/load function into the game save it where? that particular question is important as JavaScript has only limited places where it can save something at all. 1) save it on the server => call a server script with the appropriate data (e.g. via AJAX) 2) cookies, very limited storage space, only works on the same browser 3) WebStorage, more space than cookies, but still only the same browser 4) IndexedDB (same as above) Hello, Is it possible to store the edited value in the div tag in the original file, such that next time i open the HTML file the new edited value appears. Thanks in advance. Have a Good day. Hey guys, I think this is some pretty basic JavaScript but I'm not too familiar with the language and would really appreciate some help here. I have an image switcher script setup. Its very basic and changes the image displayed on click of a link. Here is what I currently have: Javascript: Code: <script type="text/javascript"> function changeIt(imageName,objName) { var obj = document.getElementById(objName); var imgTag = "<img src='"+imageName+"' border='0' />"; obj.innerHTML = imgTag; return; } </script> HTML: Code: <div id="image1"> <img src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg" border="0" alt="one" /> </div> <br> <a id="one" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/49057_100001550995222_9679_q.jpg','image1');">one</a> <a id="two" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/174411_100002333675750_7453320_q.jpg','image1');">two</a> <a id="three" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41512_100000999943382_7276_q.jpg','image1');">three</a> <a id="four" href="#" onclick="changeIt('http://profile.ak.fbcdn.net/hprofile-ak-snc4/41477_100001406980454_629_q.jpg','image1');">four</a> <a id="five" href="#" onclick="changeIt('http://www.dead-paramour.org/fans/fanMCR4.jpg','image1');">five</a> Its very basic but does what I want. What I'm attempting to do is store the image selected as a cookie so that when users refresh/navigate to other pages the image stays to the one they selected. Is anyone able to help me out with this? Any help is greatly appreciated. Thanks, Chris Hello all, i am a newbie here. I am starting to programme with javascript. I am designing a website. in This website there is an input with type = text and beside this input, there is another input with type = submit. If i open this website: The default value on the search text is "Enter a text", and if I click submit button, this button can recognize the value of the search text which is "Enter a text". <input id="searchText" type="submit" value="Enter a text"/> <input id="searchSubmit" type="submit" value="Submit"/> And then i modified a little bit. I have this javascript: var searchInput = $('#searchText'); searchInput.focus( function() { searchInput.attr('value', ''); }); The goal is, when I click on the search text, the default text is gone. And it worked. But if i write a new text on the search text, the submit button still recognized the value of search text as empty string. Can anyone please help me?? Thank you This is code use to save XML file using Javascipt but it can't not save full Processing Instruction, example we have PI is <?xml version="1.0" encoding="utf8"> when run the code then PI is saved with <?xml version="1.0"> and sometime it doesn't word. Please help me fix, thanks PHP Code: function SaveXML(xmlDoc,filename) { var outputXML = xmlDoc.xml; var mfObj = new ActiveXObject("Scripting.FileSystemObject"); var absPath = getPath(); var file = mfObj.CreateTextFile(absPath + filename, true); file.Write(outputXML); file.Close(); } function getPath() { var path = document.location; var str = new String(path); var end = str.lastIndexOf("/"); var absolutePath = str.substring(8, end) + "/"; absolutePath = absolutePath.replace(/%20/g, " "); return absolutePath; } Hey Guys, I'm working on a Gameserver for a Game, written in JavaScript. I want to save all console.log()'s with Timestamp into a txt-file but I don't know how :/ Could you help me with it and tell me how I can do this? for example, I want to save User-Logins into the logs. This is the code I'm using right now. Code: case "LOGIN": var data = PacketModels.login.parse(datapacket); User.login(data.username, data.password, data.is_banned, data.is_online, function(result, user){ if(result){ if(user.is_banned == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is banned!"); c.socket.write(packet.build(["LOGIN", "ISBANNED"])); }else if(user.is_banned == 0){ if(user.is_online == 1){ console.log("[WARNING] ".red + data.username + " tried to login. It failed because the User is already online!"); c.socket.write(packet.build(["LOGIN", "ALREADYLOGGEDIN"])); }else if(user.is_online == 0){ c.user = user; c.enterroom(c.user.current_room); c.user.is_online = 1; c.user.save(); c.socket.write(packet.build(["LOGIN", "TRUE", c.user.current_room, c.user.pos_x, c.user.pos_y, c.user.username])); console.log("[INFO] ".blue + data.username + " has logged in on Map:[" + (c.user.current_room_name).blue + "] X:[" + String(c.user.pos_x).blue + "] Y:[" + String(c.user.pos_y).blue + "]"); } } ... Reply With Quote 12-22-2014, 02:48 PM #2 sunfighter View Profile View Forum Posts Senior Coder Join Date Jan 2011 Location Missouri Posts 4,830 Thanks 25 Thanked 672 Times in 671 Posts JS will not save a text file. You need to do this with a server side language like PHP and if your going to all of that trouble you might want to study a database at the same time or soon after. Hi.. I have checkbox and I need to get his value. I create function for checkbox if checkbox is clicked it is true then the checkbox value is H else W. Code: function chk(){ if(document.getElementById('H').checked==true){ var H = document.getElementById('H'). value = H; } else if(document.getElementById('H').checked==false){ var H = document.getElementById('H'). value = W; } } and I have function for save : Code: function ApproveLeaveOP(){ var H = document.getElementById('H').value; document.sampleform.action="AddLeave.php?H="+H; document.sampleform.submit(); } <input type="checkbox" name="H" id="H" value="" onclick="chk()"> I don't know how can I add value to the checkbox if I click the value will be H if not the value is W. I am new in using checkbox. Thank you so much.. Hi all, I found this script online that lets users on an iPhone drag boxes around the screen. The problem is that when you reload the page, the boxes are in different positions than what they were before the reload. Like, you would drag the boxes around and then reload the page, but the boxes would be in the default locations. I want the boxes to stay in the same spot that they were the previous time they moved them. Does that make sense? Anyways, here's the example I found online: http://www.manifestinteractive.com/iphone/touch/ Only works on iPad/iPhone/iPod Touch. It uses jQuery too so if you know of any way to do this, that would be excellent. Thanks. I am trying to do this and have some code im working with. I can load the file through a browse button then save it using the existing code. However, I want instead of the browse option to just preload the file into the textarea and then be able to save it. Code: <script language="javascript"> <!--// var oFileSystem; oFileSystem = new ActiveXObject("Scripting.FileSystemObject"); function ShowFile(sFilePath){ frmEditHTML.tarHTMLText.value = oFileSystem.OpenTextFile(sFilePath).ReadAll(); } function SaveAfterEditing(){ var oFile; oFile = oFileSystem.CreateTextFile(frmEditHTML.filPath.value,1); oFile.WriteLine(frmEditHTML.tarHTMLText.value); oFile.Close(); } </script> Code: <form name="frmEditHTML"> <input type="file" name="filPath" onchange="ShowFile(this.value)"> <br><textarea name="tarHTMLText" cols=60 rows=20></textarea><br> <input type="button" value="Save" name="cmdSave" onclick="SaveAfterEditing()"> </form> im trying to have it save the values in the menu, i was think either cookies or storing it in the .window thing but i am unsure of how to do these, any help would be great. Code: <script type="text/javascript"> function setCookie(c_name,value,exdays) { var exdate=new Date(); exdate.setDate(exdate.getDate() + exdays); var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString()); document.cookie=c_name + "=" + c_value; } function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name) { return unescape(y); } } } <!-- // initialise shortcuts on page load var selectObj1=null, selectObj2=null// global function init() { selectObj1=document.getElementById("select_1"); selectObj2=document.getElementById("select_2"); selectObj2.disabled=true; // ========== end init() ============== // second select box options list var A= new Array() A["remote 1"]=["0","yup","DVD-1"]; A["remote 2"]=["0","VCR-1","DVD-2"]; // // global variables var saveObj=null, indx=null, targetObj=null, selectNo=null; // function process(obj,sNumb) { // disable unused select boxes if(sNumb==1) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } else if( sNumb==2) { selectObj1.selectedIndex="0"; selectObj1.disabled=true; } // // store selected index indx=obj.options.selectedIndex; // invalid selection if(indx==0){ return; } // --------- // save passed parameters for use after timeout deleay saveObj=obj, selectNo=sNumb; // put object items list into next select box after clearing targetObj=document.getElementById("select_"+selectNo) targetObj.disabled=false; // clear any existing options note that this starts from end of list, not beginning for(var i=targetObj.options.length-1;i>-1;i--) { targetObj.options[i]=null; } // build in short delay here to avoid error in Opera browser setTimeout("finishOff()",50) } // ----------- 50ms delay here -------- // called from timeout in function process() function finishOff() { var obj=saveObj; // from global // fill selectObj options var i, thisItem=0; // build options list switch(selectNo){ case 2 : targArray = A[obj.options[indx].value]; break; } // for(i=0;i<targArray.length;i++) { thisItem=targArray[i]; // syntax is new Option("text", "value", isDefaultSelectedFlag, isSelectedFlag) targetObj.options[i]=new Option(thisItem,thisItem,false,false); } obj.blur(); } // ============ end process() =================== // fires on selecting in third select box function finish() { select("["+selectObj1.value+"] ["+selectObj2.value+"]") } // ------------ // window.onload=init; //--> </script> Hi , i have got this img src html.. how do i write a javascript to auto save this image in C:\ without right click on the image? <img src="/user_images/V/VI/VIR/Virgo001/1135356474_ylittlekid.jpg" alt="1135356474_ylittlekid.jpg"></img> thanks for help! I have a long survey form and once its submitted it gets recorded into a database. I would love to be able to save a PDF version of the HTML form with all their radio buttons and textfields filled out at the same time its submitted. It would need a unique name that matches their record in the database (maybe it pulls the data that was entered into one of the form fields for the name). Whether it gets uploaded to an ftp or just emailed to a mailbox doesn't really matter. The purpose of this is to basically have a visual interpretation of the data by a single user. Is something like this even possible? I'm trying to find the best approach for saving the checked value of a checkbox in SQL With this script the FieldName "Active" toggles yes/no onClick... That we can post to the database no problem... What I am having trouble with is saving the checked value. I want to make the FieldName Active =hidden, and only display the checkbox with correct value checked yes/no. Code: <script type="text/javascript"> var YesOrNo = (function() { if(document.select.checkbox.checked) { document.select.Active.value = 'yes'; } else { document.select.Active.value = 'no'; } }); </script> <form name="select"> <input type="hidden" name="Active" size="10" /> <input type="checkbox" name="checkbox" onclick="YesOrNo();" value="on" /> </form> Hello, i m new Javascript but knows basics of functions etc. ive created a website, which also has field to Submit Email addresses for newsletters.. Now, i have a TextBox (for users to write email addresses) and a Submit button in which i want to call a Javascipt script function which OnClick takes the value(email address) from the textbox and saves it to a .txt file on server. i think i am just missing a single line, the function name which will store the value.. i searched ovr the net but didnt find it.. plz help mee. Thankyou! Hi, In Google Chrome the 'chrome.tabs.captureVisibleTab(integer windowId, function callback)' method will return a data URL of the JPEG encoding of the visible area of the captured tab. We want to save that content as image to hard disk without opening/passing the contents into new html page. Does anybody know how it can be done by javascript. Please provide help. Thanks. |