Javascript AJAX file download - ajax

Is it possible to do something like this?
$.post( '/generate/file', json_data_striginfied, function( data ) {
var win = window.open()
window.write(data)
});
where data returned is binary data (a PDF file)?
I've tried it and the new window contains the binary data as text, it doesn't force a download. I would like it to force a download of the PDF file.

Try to add the remote PDF url to the new window source url.

Related

Pass Pasted Clipboard Image From CKeditor to Dropzone

We currently have code that handles all our image uploads via Dropzone.js. This includes functionality to paste from the clipboard and upload via dropzone.js, which currently works. This is that event code:
document.onpaste = function(event)
{
alert('pasted');
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
for (index in items) {
var item = items[index];
if (item.kind === 'file') {
// adds the file to your dropzone instance
myDropzone.addFile(item.getAsFile());
}
}
}
Following this, we have added a CKEditor (v4.10) html text editor to that page. The CKEditor has its own clipboard handling built in. If you activate the CKEditor (for example by clicking the text area), the CKEditor effectively takes control of the clipboard from that point. Which is correct, because we want the editor to be able to copy and paste text still.
However, CKEditor does not natively have image uploading built into it. It requires a plugin. But we would prefer not to use this plugin, and rather intercept the paste event, and if the data pasted is an image, pass that along to our dropzone.js handler instead.
While I am able to intercept that event, I am not sure what event data (if any) I can extract from the CKEditor paste event to pass along to the Dropzone handler. Here is the code so far:
var editor = CKEDITOR.instances.NoteText;
editor.on( 'paste', function( event )
{
alert('pasted ck');
console.dir(event);
//myDropzone.addFile(item.getAsFile());
} );
I have tried inspecting the event to see if anything is available for me to use, but don't seem to find anything.
Is what I'm trying to accomplish possible? Is it possible for me to somehow find and pass along the pasted event data from CKEditor to DropZone? Or am I going to have to implement the CKEditor image upload plugin?
Thanks.

Show images inside a pdf created with Gloogle Apps Script Blob

I am creating PDF files using blobs in Google Apps Script from a HTML code, but the problem is that HTML code has an image (referenced by "http") but the created pdf can't show it.
This is my code
function createBlobPDF(myMessage,myTitle){
var blobHTML = Utilities.newBlob(myMessage, "text/html", myTitle+ ".html");
var myPDF = blobHTML.getAs("application/pdf");
return myPDF;
}
Any solution? thanks!!
If the images in HTML are loaded from URLs, the converted PDF file doesn't include the images. If you want to include the images in the converted PDF file, please put the images to HTML as base64 data.
In order to confirm this situation, please see the following sample script. This sample script puts an image as URL and base64 data. The result is displayed them to a dialog and created a PDF file.
When you use this script, please copy and paste to the script editor of Spreadsheet.
Sample script :
function myFunction() {
// image
var url = "https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a";
var blob = UrlFetchApp.fetch(url).getBlob();
var b64 = blob.getContentType() + ';base64,'+ Utilities.base64Encode(blob.getBytes());
var html = "URL<img src=\"" + url + "\">Base64<img src=\"data:" + b64 + "\">";
var h = HtmlService.createHtmlOutput(html);
// Open dialog with the images.
SpreadsheetApp.getUi().showModalDialog(h.setWidth(500).setHeight(200), 'Sample');
// Create from HTML to PDF file.
DriveApp.createFile(h.getAs("application/pdf").setName("text.pdf"));
}
Result of dialog :
Both images can be seen.
Result of PDF file :
Only the image of base64 can be seen.
Note :
This is a simple script. So please modify this to your environment.
References :
How to display Base64 images in HTML?
If I misunderstand your question, I'm sorry.
I tested converting html to pdf with image content. It works but in the bottom of a box, the color does not work! How to make the color to appear in the background of a box?
I wanted to show you my little treatment as an example "<>" but it doesn't work because there is no window for code.gs . Shame...
In short, see the final result in pdf, attached
before clicking on the "validate" button, the screen is displayed, see the screenshot below. this is where you "capture" the HTML presentation and then run to convert HTML to PDF.
after clicking on "validate", here is the result, see below :
normally, I would like to have the same result between screen and PDF.
Then, how to do it ?

Dropzone - Replace filename with link after upload is complete?

I've integrated dropzone and it's working fine with the files getting uploaded etc. What I'd like to do is hide the progress bar once the upload is successful and replace the filename with a link to the actual upload file automatically. This would happen automatically as each file finished uploading...
Looking at the documentation, I know I should use
this.on("success", function(file, response) {
if (response.success == 'true') {
// hide progress bar '.dz-progress'
// replace .data-dz-name with url from response
}
});
However, I haven't been able to figure out how to get access to that specific html element to replace/hide etc.
Edit: I was able to use css classes from the original dropzone.css to hide/transition the progress bar. Now just need to find a way to replace the filename with an 'a' tag.
For Dropzone 5.x and above
The correct way to update the thumbnail is by modifying the Preview Template in the success callback as follows:
this.on("success", function(file, response) {
// modify the preview template
file.previewTemplate.appendChild(document.createTextNode(response.filePath));
});
Reference tutorial for Dropzone along with server side handling
$('.dz-progress').hide();
or
$(".dz-progress").remove();
and to replace .data-dz-name
$('.data-dz-name').html(url from response);

Content-Disposition inline filename issue with IE

I am displaying a pdf in browser with inline from API using an aspx page.
While saving the pdf using Chrome/Firefox, takes the filename from header("Content-Disposition", "inline;filename=xyz.pdf")
But while saving the pdf using IE it does not reads the filename from header("Content-Disposition", "inline;filename=xyz.pdf"). instead it takes the aspx name.
Technical details
I have an xyz.aspx page.
The xyz.aspx page will invoke an API for a document.
Then the downloaded document from API will transferred to browser with inline to display the pdf document.
Am setting the response header as below and writing the file bytes.
HttpContext.Current.Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "inline;filename=\"" + Name + "\"");
HttpContext.Current.Response.ContentType = "application/pdf";
Issue:
While saving the opened pdf in IE it takes xyz.aspx instead of the name from header.
Requirement:
While saving the pdf using IE, it need to save with the name of pdf.
I googled so much, as every one tells its IE behavior. I hope some one knows a solution.
Note: I have to display the pdf in browser and then save. Not to download using "attachment"
It is true some versions of IE can't handle ("Content-Disposition", "inline;filename=...")
This is because filename=... was originally intended for the attachment disposition. Not all browser-based PDF viewers can handle it.
The only solution I see is to allow access via a different url.
Suppose you have a route to the pdf like: /pdf/view. If you change it to /pdf/view/filename and you configure your application to handle this route in the same way as /pdf/view your problem is solved.
You can also re-write the download url on the webserver.
Depending on your webserver you have various ways of doing this.
I have also tried with all kind of headers and methods.
In the end, my solution was
private FileResult ReturnStreamAsPdf(string fileName, Stream stream)
{
ContentDisposition cd = new ContentDisposition
{
FileName = fileName,
Inline = true // false = prompt the user for downloading; true = browser to try to show the file inline
};
Response.Headers.Add("Content-Disposition", cd.ToString());
Response.Headers.Add("X-Content-Type-Options", "nosniff");
return new FileStreamResult(stream, MediaTypeNames.Application.Pdf);
}
and the Route Attribute on the method:
[Route("api/getpdfticket/{ticketnumber}")]
public async Task<FileResult> GetPdfTicket(string ticketnumber)
And the href:
href="#($"/api/getpdfticket/{product.TicketNumber}.pdf")"
It seems like Microsloft is still inventing their own standards:
http://test.greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf
PDF Handler : content-disposition filename

Generate save as dialog box with AJAX request in Ext Js

I have an application that contains a grid and button for the user to be able to export the grid to excel. I want to be able to show the save as dialog box when the server responds with the excel file.The server accepts the parameters as a JSON object. Here is my code:-
Ext.Ajax.request({
url: '/export/excel/',
method: 'POST',
//Send the query as the message body
jsonData: jsonStr,
success: function (result,request) {
Ext.DomHelper.append(document.body, {
tag: 'iframe',
frameBorder: 0,
width: 0,
height: 0,
//src:result,
css: 'display:none;visibility:hidden;height:1px;'
});
}, //success
failure: function (response, opts) {
var msg = 'server-side failure with status code: ' + response.status + ' message: ' + response.statusText;
Ext.Msg.alert('Error Message', msg);
}
});
I know there is a similar question ( ExtJS AJAX save as dialog box) but that references a static file on the server.In my case, depending upon the json sent the result is going to be different each time. I get back the entire excel file that i want in the result.responseText. What needs to be done so that the dialog box popup up asking the user for save as options? Also, im not sure how the src in the domhelper should be configured. Any help would be really appreciated.
I believe the only way to do this in a totally client agnostic way is to force it from the server-side using a Content-Type of: octect-stream and Content-Disposition of 'attachment' with a suggested filename. See:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html#sec19.5.1
and
http://www.ryboe.com/tutorials/php-headers-force-download
You can also use so-called 'dataURIs' but they have their own set of issues:
http://en.wikipedia.org/wiki/Data_URI_scheme
My recommendation would be to return EXCEL content dynamically on the server and just make the button a link to that url that POSTS the current data your working with and sets the correct response headers to trigger your browser to download the file. Since you are doing an AJAX call and not letting the web-browser get the URL directly, any HTTP headers you set to control the way the browser interprets the content won't matter because you are doing it in JS not in the user's browser. By returning the content directly to the user through a link on the server, you'll get around this problem.
Since you actually want the user to click on the link, I don't think AJAX is appropiate here.
I made the server side return the path of the location the file is created and saved, instead of sending the file as an attachment in the response and hence avoiding the problem of setting the headers in the response. Then i just set the source of the iframe in the code to the path that gets returned in the response (result.responseText).

Resources