Downloading a PDF from an HTTP POST call - forms

Here is what I'm trying to accomplish (IE 9+, Chrome, FF, Safari) without the use of JQuery:
Make an http POST call to my API endpoint with some data
Server dynamically generates a PDF and returns the PDF as a binary attachment
Browser does default download behavior and downloads the PDF without refreshing the page
Basically I want to get the behavior similar to <a href="test.pdf"> but for a dynamically generated PDF after making a POST call instead of a GET call.
I've tried lots of different things, but they either didn't work cross browser (such as using $window.open() with a blob URL), were blocked by popup blockers (any $window call outside of the click scope), or didn't cause the PDF to be automatically downloaded (any $http POST solution).
I finally found one solution that seems to work which creates a form using javascript and submits it.
var form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', myurl);
var params = {foo: 'bar'};
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', key);
hiddenField.setAttribute('value', params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
This successfully accomplishes the 3 steps above, but now I've run into a new problem. There is no way to determine when the PDF file has been successfully downloaded. This is preventing me from removing the form and from displaying a friendly 'Please wait...' message to the user. There is also the additional problem that submitting the form cancels any outstanding ajax requests as well which isn't optimal.
I have full control over both the server and the client, so what's the best way to fix this? I don't want to have to save the PDF on the server so passing back a url and doing a second GET request from the client won't work in this case. Thanks!

You can make an server response behave as a download by applying some HTTP headers:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="SOME_NAME.pdf"
Content-Transfer-Encoding: binary
If you're initiating the download through JS only (instead of having the user click a download link), then check out this question for some caveats.
Update: Syntax for POST
Better Update: Form solution with iframe target
You can detect that your server-side script has finished (and subsequently, that the download is ready to begin) by having the form target an iframe. I believe this should also fix the issue of cancelling outstanding Ajax calls, but I'm not certain. Here is the code to do it (just stick this into your code example after the for loop and before document.body.appendChild(form);):
var frame = document.createElement('iframe');
frame.setAttribute('id', 'pdfFrame');
frame.onload = function(){
document.body.removeChild(form);
document.body.removeChild(frame);
alert('Download ready!');
}
document.body.appendChild(frame);
form.setAttribute('target', 'pdfFrame');
You can replace my alert with your code to remove the 'Please wait...'.

Related

CODEIGNITER 3: save a whole page response to a file before sending it to client browser

I want to save a page to a file in CODEIGNITER 3 - a whole page just before the page is sent to a browser. But I don't know how to do it and the most important is where to process the page in Codeigniter 3 code?
Oh, I was lucky to find it somehow in my code:
https://codeigniter.com/userguide3/general/hooks.html?highlight=display_override
display_override Overrides the _display() method, used to send the
finalized page to the web browser at the end of system execution. This
permits you to use your own display methodology. Note that you will
need to reference the CI superobject with $this->CI =& get_instance()
and then the finalized data will be available by calling
$this->CI->output->get_output().

How to make REST call to MS Graph/OneDrive method with OAuth2

I am trying to use the OneDrive API and I have successfully registered my app through their Application Registration Portal. I can call successfully call the Javascript FilePicker SDK to upload and download files
That demonstrates that I have my app registered properly and the proper app/client-id's.
Now I'd like to use the REST services to upload and download files but I'm not sure how to send authentication and I don't know how to make the call to the proper URL.
My first question is: How can I use the token I created in the reg service to make a REST call?
My second question is: What syntax should I use to upload a file? I don't know where to put the URL to make the call.
The PUT documentation for their upload is found here
<script type="text/javascript">
function launchSaveToOneDrive(){
var xhttp = new XMLHttpRequest();
//Authorization: bearer {token}
xhttp.open("PUT", "/drive/items/{parent-id}:/{filename}:/content", false);
xmlhttp.setRequestHeader("Authorization", "Bearer-xxxxxxxxxxxxxxxxxxx");
xhttp.setRequestHeader("Content-type", "text/plain");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
</script>
One option is to use the Microsoft Graph JavaScript SDK that can help with REST calls including uploading files to OneDrive through the MS Graph. The library works with client side JavaScript and Node for JavaScript server apps.
Check the Browser folder under samples to see how to use the SDK in a client app. Uploading a file would look something like this (see that link for the full code):
// file variable is from the contents of an input field for example
var file = document.querySelector('input[type=file]').files[0];
// after user selects a file from the file picker
client
.api('/me/drive/root/children/Book.xlsx/content')
.put(file, (error, response) => {
// supports callbacks and promises
});

How to clear the file data from a multipart jsp

I have a JSP form with form property (In order to submit multiple files) as
enctype = "multipart/form-data";
encoding = "multipart/form-data";
When the form get submitted I'm reading the form data as
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List<FileItem> fileItemList = fileUpload.parseRequest(request);
Now the issue I'm facing is that after the servlet process the request I'm coming back to the same page, after which if the user refreshes the page than based on the previous action performed the form is getting submitted again to the same servlet and I'm again getting the file which has been previously browsed and it's saving again.
Is there is any way we can clear the file information which has been browsed ?
Thanks
Your HTML code would have helped here. However, here is a solution that I think could help you resolve the issue.
You can reset the files associated with the file upload control by using
document.getElementById('yourFileInputControlId').files = '';
This should be done in java script immediately after your file upload request has been handled.(I am considering you are uploading your file using ajax)
If you are actually submitting the entire form rather than using Ajax, I do not see a reason why the file control would not reset. Please provide more details by editing the question if you still face the issue

Simplest example for sending post data via links in Zend Framework

Starting with Zend and I´d like to know what is the simplest way of sending POST data to another page, not by forms, but by some link in my view instead. Thanks :)
You can't send POST data through a link. At least not through a normal link. Link can only carry GET data.
If you need to send POST over a link it's most certainly a design flaw.
If you're 100% sure, that you need it, you can do that using jQuery and onclick event. It`s not possible to do it without javascript. Other option would be to send it using form with hidden fields with single submit button visible - that would even work without javascript.
Normal hyperlinks in HTML are sent with GET requests and are not supposed to change the state of the resource being accessed. This is known as being idempotent. You can repeat the request over and over, and the result of each succeeding request to the same URL is the same as the first one.
POST requests don't have this restriction and are intended for when the user needs to change something (such as creating a new resource.)
It's not possible to send a POST request via a normal HTML link. And even if you find a way, it breaks an almost universal expectation that web users have. What are you trying to accomplish? Maybe there's a better way.
But to answer your question, you could use something like jQuery to capture the "click" event and make it do a POST request:
$('.my-link').click(function() {
var url = $(this).attr('href');
var data = {};
$.post(url, data, function() {
window.alert('success!');
});
return false;
});
If your URL has any query parameters, i.e. "?foo=bar&baz=bum", then you'd probably need to strip them off of the URL and pass them as a second parameter to the $.post() function. This is left as an exercise for the reader. ;-)

Preventing form resubmission

Page one contains an HTML form. Page two - the code that handles the submitted data.
The form in page one gets submitted. The browser gets redirected to page two. Page two handles the submitted data.
At this point, if page two gets refreshed, a "Confirm Form Resubmission" alert pops up.
Can this be prevented?
There are 2 approaches people used to take here:
Method 1: Use AJAX + Redirect
This way you post your form in the background using JQuery or something similar to Page2, while the user still sees page1 displayed. Upon successful posting, you redirect the browser to Page2.
Method 2: Post + Redirect to self
This is a common technique on forums. Form on Page1 posts the data to Page2, Page2 processes the data and does what needs to be done, and then it does a HTTP redirect on itself. This way the last "action" the browser remembers is a simple GET on page2, so the form is not being resubmitted upon F5.
You need to use PRG - Post/Redirect/Get pattern and you have just implemented the P of PRG. You need to Redirect. (Now days you do not need redirection at all. See this)
PRG is a web development design pattern that prevents some duplicate form submissions which means, Submit form (Post Request 1) -> Redirect -> Get (Request 2)
Under the hood
Redirect status code - HTTP 1.0 with HTTP 302 or HTTP 1.1 with HTTP 303
An HTTP response with redirect status code will additionally provide a URL in the location header field. The user agent (e.g. a web browser) is invited by a response with this code to make a second, otherwise identical, request to the new URL specified in the location field.
The redirect status code is to ensure that in this situation, the web user's browser can safely refresh the server response without causing the initial HTTP POST request to be resubmitted.
Double Submit Problem
Post/Redirect/Get Solution
Source
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
The only way to be 100% sure the same form never gets submitted twice is to embed a unique identifier in each one you issue and track which ones have been submitted at the server. The pitfall there is that if the user backs up to the page where the form was and enters new data, the same form won't work.
There are two parts to the answer:
Ensure duplicate posts don't mess with your data on the server side. To do this, embed a unique identifier in the post so that you can reject subsequent requests server side. This pattern is called Idempotent Receiver in messaging terms.
Ensure the user isn't bothered by the possibility of duplicate submits by both
redirecting to a GET after the POST (POST redirect GET pattern)
disabling the button using javascript
Nothing you do under 2. will totally prevent duplicate submits. People can click very fast and hackers can post anyway. You always need 1. if you want to be absolutely sure there are no duplicates.
You can use replaceState method of JQuery:
<script>
$(document).ready(function(){
window.history.replaceState('','',window.location.href)
});
</script>
This is the most elegant way to prevent data again after submission due to post back.
Hope this helps.
If you refresh a page with POST data, the browser will confirm your resubmission. If you use GET data, the message will not be displayed. You could also have the second page, after saving the submission, redirect to a third page with no data.
Well I found nobody mentioned this trick.
Without redirection, you can still prevent the form confirmation when refresh.
By default, form code is like this:
<form method="post" action="test.php">
now, change it to
<form method="post" action="test.php?nonsense=1">
You will see the magic.
I guess its because browsers won't trigger the confirmation alert popup if it gets a GET method (query string) in the url.
The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.
Usually, I will take actions below to prevent resubmission:
Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.
Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.
In most of the occasions, these measures can help to prevent resubmission.
I really like #Angelin's answer. But if you're dealing with some legacy code where this is not practical, this technique might work for you.
At the top of the file
// Protect against resubmits
if (empty($_POST)) {
$_POST['last_pos_sub'] = time();
} else {
if (isset($_POST['last_pos_sub'])){
if ($_POST['last_pos_sub'] == $_SESSION['curr_pos_sub']) {
redirect back to the file so POST data is not preserved
}
$_SESSION['curr_pos_sub'] = $_POST['last_pos_sub'];
}
}
Then at the end of the form, stick in last_pos_sub as follows:
<input type="hidden" name="last_pos_sub" value=<?php echo $_POST['last_pos_sub']; ?>>
Try tris:
function prevent_multi_submit($excl = "validator") {
$string = "";
foreach ($_POST as $key => $val) {
// this test is to exclude a single variable, f.e. a captcha value
if ($key != $excl) {
$string .= $key . $val;
}
}
if (isset($_SESSION['last'])) {
if ($_SESSION['last'] === md5($string)) {
return false;
} else {
$_SESSION['last'] = md5($string);
return true;
}
} else {
$_SESSION['last'] = md5($string);
return true;
}
}
How to use / example:
if (isset($_POST)) {
if ($_POST['field'] != "") { // place here the form validation and other controls
if (prevent_multi_submit()) { // use the function before you call the database or etc
mysql_query("INSERT INTO table..."); // or send a mail like...
mail($mailto, $sub, $body); // etc
} else {
echo "The form is already processed";
}
} else {
// your error about invalid fields
}
}
Font: https://www.tutdepot.com/prevent-multiple-form-submission/
use js to prevent add data:
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}