How to download a file with a very long URL? - javascript

Basically I'm trying to trigger the download of a file which is constructed dynamically. In order to construct the file I need to pass a lot of information to the servlet.
This means I can't use GET, I should use POST instead.
In order for the download not to mess the application up, though, I must open a new window. The problem is that I cannot do this:
window.open(http://very.long.url.com/.../, "_blank");
since this would cause the URL limit to be exceeded and GET to be used instead of POST.
All information that needs to be sent to the servlet are in an object called "config.
My solution was to write a form in the new window with POST method, then add hidden inputs to it and then trigger the submit, like this:
var win = window.open("about:blank", "_blank");
win.document.write("<form method='post' id=donwload action='serveletURL'></form>");
$.each(config, function (name, value) {
var fragment = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = '<input type=\'hidden\' name=\'' + name + '\' value=\'' + value + '\'></input>';
while (temp.firstChild) {
fragment.appendChild(temp.firstChild);
}
win.document.getElementById("download").appendChild(fragment);
});
win.document.getElementById('download').submit();
And it works in Google Chrome and Firefox, but it doesn't work on IE. On IE (even IE 10), a download dialog with a "serveletURL" file name opens and nothing gets downloaded when I ask the file to be saved or opened.
I'm sure I'm missing something... How do I accomplish this??
Thank you!
Eduardo

Related

Add attachment by url to Outlook mail

The context
There is a button on the homepage of each document set in a document library on a SharePoint Online environment. When the button is clicked, an Outlook window opens with the title and body set and all the files in the document set should be added as the attachments.
The code
Here's the code I have so far:
var olApp = new ActiveXObject("Outlook.Application");
var olNs = olApp.GetNameSpace("MAPI");
var olItem = olApp.CreateItem(0);
var signature = olItem.HTMLBody;
signature.Importance = 2;
olItem.To = "";
olItem.Cc = "";
olItem.Bcc = "";
olItem.Subject = "Pre filled title";
olItem.HTMLBody =
"<span style='font-size:11pt;'>" +
"<p>Pre filled body</p>" +
"</span>";
olItem.HTMLBody += signature;
olItem.Display();
olItem.GetInspector.WindowState = 2;
var docUrl = "https://path_to_site/Dossiers/13245_kort titel/New Microsoft Word Document.docx";
olItem.Attachments.Add(docUrl);
The Problem
When I run this code, an Outlook window opens with everything set correctly. But on the line where the attachment is added I get following very vague error message:
SCRIPT8: The operation failed.
I thought it could be the spaces in the url so I replaced them:
docUrl = docUrl.replace(/ /g, "%20");
Also didn't work (same error) and providing all parameters like this also didn't work:
olItem.Attachments.Add(docUrl, 1, 1, "NewDocument");
Passing a path to a local file (e.g. C:/folder/file.txt) or a publicly available url to an image does work. So my guess is it has something to do with permissions or security. Does anybody know how to solve this?
PS: I know using an ActiveX control is not the ideal way of working (browser limitations, security considerations, ...) but the situation is what it is and not in my power to change.
You cannot pass a url to MailItem.Attachments.Add in OOM (it does work in Redemption - I am its author - for RDOMail.Attachments.Add). Outlook Object Model only allows a fully qualified path to a local file or a pointer to another item (such as MailItem).

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);

What is wrong with my javascript for a browser I would like to create?

I know you people will think I am insane, and thus an idiot, but I really have a serious question, well at least to me. What is wrong with my javascript for a browser I would like to create?It will not open the URL in the iframe. I am creating an html source file with some javascript to split a "get" url,and echo the resulting variable into an iFrame. I wanna use Webkit as the rendering engine, so I'm using Google Chrome to create an application shortcut. Yes, I know it will require google chrome, but this is just a test.
function goTo(){
var urlb = window.location.href;
var urla = urlb.split('localhost/browser.html?url=');
var urlc = urla[1];
var urld = urlc.replace("+"," ");
var urle = urld.replace("%3A ",":");
var urlg = urle.replace("%2F","/");
var url = urlg;
document.getElementByID('url').innerHTML="<iframe src=' . url . "'width='100%'
height='90%'></iframe> Opened:" . url ."</div>";
}
This is the javscript function to open the url. I am pretty sure you would think that the html is just a simple input form and the blank Iframe, which it is.
Please help me if you can.
When you are trying to get the URL, you want to use decodeURIComponent(). Don't make up your own function to unescape the data. Also, get the query string parameters properly. See this StackOverflow post: https://stackoverflow.com/a/901144/362536
Now that you have the proper URL, don't simply inject it into your HTML. You're opening yourself up to security troubles, and a broken browser when you run into characters you don't expect. Create the iframe, then set its attributes programmatically. https://stackoverflow.com/a/710347/362536
Finally, fix your syntax errors.

Do we need a web server (like Apache) to access a .json file?

I was trying to read an info.json file, using the jQuery API. Please find the code below, which is part of test.html.
$.getJSON('info.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
The test.html file resides on my local machine and when I try to open it in the browser, the Ajax call is not getting triggered and the info.json file is not read.
Is it not working because I don't have a web server? Or am I doing anything wrong in the code? (I don't see any errors in the Firebug console though).
Thanks in advance.
You will always have to host your site from where you are making AJAX call. Otherwise it will throw this exception.
origin null is not allowed by access-control-allow-origin
Host your page on localhost server and I guess everything will work nicely.
While technically you don't need a web server for this, some of the libraries you use to abstract network access may not work with local files and some browsers don't let local files do a lot, so something like a little test web server for static files would be very useful for your development and testing.
Install a small webserver like http://jetty.codehaus.org/jetty/
easy to install, and small download ;)
By putting your JSON string into a text file and loading it in a iframe, you can extrapolate the data. (Most browsers can load .txt files in iframes.)
var frame = document.createElement("IFRAME"); //Create new iframe
var body = document.body;
frame.onload = function() { //Extrapolate JSON once loaded
data = JSON.parse(frame.contentDocument.documentElement.innerText); //Loads as a global.
body.removeChild(frame); //Removes the frame once no longer necessary.
}
frame.style.display = "none"; //Because the frame will have to be appended to the body.
body.appendChild(frame);
frame.src = "your JSON.txt"; //Select source after the onload function is set.

Is robust javascript-only upload of file possible

I want a robust way to upload a file. That means that I want to be able to handle interruptions, error and pauses.
So my question is: Is something like the following possible using javascript only on the client.
If so I would like pointers to libraries, tutorials, books or implementations.
If not I would like an explanation to why it's not possible.
Scenario:
Open a large file
Split it into parts
For each part I would like to
Create checksum and append to data
Post data to server (the server would check if data uploaded correctly)
Check a web page on server to see if upload is ok
If yes upload next part if no retry
Assume all posts to server is accompanied by relevant meta data (sessionid and whatnot).
No. You can, through a certain amount of hackery, begin a file upload with AJAX, in which case you'll be able to tell when it's finished uploading. That's it.
JavaScript does not have any direct access to files on the visitor's computer for security reasons. The most you'll be able to see from within your script is the filename.
Firefox 3.5 adds support for DOM progress event monitoring of XMLHttpRequest transfers which allow you to keep track of at least upload status as well as completion and cancellation of uploads.
It's also possible to simulate progress tracking with iframes in clients that don't support this newer XMLHTTPRequest additions.
For an example of script that does just this, take a look at NoSWFUpload. I've been using it succesfully for about few months now.
It's possible in Firefox 3 to open a local file as chosen by a file upload field and read it into a JavaScript variable using the field's files array. That would allow you to do your own chunking, hashing and sending by AJAX.
There is some talk of getting something like this standardised by W3, but for the immediate future no other browser supports this.
Yes. Please look at the following file -
function Upload() {
var self = this;
this.btnUpload;
this.frmUpload;
this.inputFile;
this.divUploadArea;
this.upload = function(event, target) {
event.stopPropagation();
if (!$('.upload-button').length) {
return false;
}
if (!$('.form').length) {
return false;
}
self.btnUpload = target;
self.frmUpload = $(self.btnUpload).parents('form:first');
self.inputFile = $(self.btnUpload).prev('.upload-input');
self.divUploadArea = $(self.btnUpload).next('.uploaded-area');
var target = $(self.frmUpload).attr('target');
var action = $(self.frmUpload).attr('action');
$(self.frmUpload).attr('target', 'upload_target'); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', '/trnUpload/upload'); //change the form's action to the upload iframe function page
$(self.frmUpload).parent("div").prepend(self.iframe);
$('#upload_target').load(function(event){
if (!$("#upload_target").contents().find('.upload-success:first').length) {
$('#upload_target').remove();
return false;
} else if($("#upload_target").contents().find('.upload-success:first') == 'false') {
$('#upload_target').remove();
return false;
}
var fid = $("#upload_target").contents().find('.fid:first').html();
var filename = $("#upload_target").contents().find('.filename:first').html();
var filetype = $("#upload_target").contents().find('.filetype:first').html();
var filesize = $("#upload_target").contents().find('.filesize:first').html();
$(self.frmUpload).attr('target', target); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', action); //change the form's
$('#upload_target').remove();
self.insertUploadLink(fid, filename, filetype, filesize);
});
};
this.iframe = '' +
'false' +
'';
this.insertUploadLink = function (fid, filename, filetype, filesize) {
$('#upload-value').attr('value', fid);
}
}
$(document).ready(event) {
var myupload = new Upload();
myupload.upload(event, event.target);
}
With also using PHP's APC to query the status of how much of the file has been uploaded, you can do a progress bar with a periodical updater (I would use jQuery, which the above class requires also). You can use PHP to output both the periodical results, and the results of the upload in the iframe that is temporarily created.
This is hackish. You will need to spend a lot of time to get it to work. You will need admin access to whatever server you want to run it on so you can install APC. You will also need to setup the HTML form to correspond to the js Upload class. A reference on how to do this can be found here http://www.ultramegatech.com/blog/2008/12/creating-upload-progress-bar-php/

Categories

Resources