Redirect after downloading the pdf in spring - spring

I'm using spring boot. I wrote code to upload data to database. If something goes wrong, data will be downloaded as a pdf which is wrong. What I want to do is, I have to download that pdf and direct to another page.
#RequestMapping(value = "/doUpload", method = RequestMethod.POST)
public void doUpload(#ModelAttribute("employeeCsvForm") EmpFileUpload fileUpload,HttpServletRequest request, HttpServletResponse response){
// codes for create pdf.
if (errorCount != 0) { //errorCount is the count of error data
File fileEmp = new File("error.pdf");
//downloading the pdf in browser path
if (fileEmp.exists()) {
FileUtils.copyFile(fileEmp, response.getOutputStream());
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "attachment;filename=error.pdf");
response.flushBuffer();
}
}
}
This code downloads the pdf file. But I have to redirect to another page, So I used
response.sendRedirect(request.getContextPath() + "/employee/errorCsv"); after response.flushBuffer(); Its downloading pdf successfully but showing following error.
Error is : getOutputStream() has already been called for this response
When I write the redirect code response.sendRedirect(request.getContextPath() + "/employee/errorCsv"); before response.flushBuffer(); Its directing to other page successfully but not downloading.
I want to do both, I tried my best, but failed. Thanks in advance.

You cannot redirect after you initiate a download.
That's why every page that redirects upon download (think Sourceforge for example) does this by:
first redirecting you to the target page
waiting a couple seconds (possibly optional, but might help load the target page)
then initiating a download using Javascript (for browser, this is in fact another redirect)
Technically, a HTTP redirect is part of HTTP headers. Headers are sent over HTTP before any actual content and cannot be sent once you start sending the body (content) - that's why you got the error.
To the browser, a download is just a special kind of page visit - one that ends up downloading data instead of showing it as a website. Now, you only can initiate a redirect (i.e. direct the browser to visit another page) in a website, you cannot do this if downloading. So the following order of steps cannot possibly work:
Visit initial page
At the initial page, direct browser to download file
Direct browser to visit target page
So what you have to do is swap the steps:
Visit initial website
At the initial page, direct browser to visit target page
At the target page, direct browser to download file

Related

ModelAttribute is not getting set after forcing a download

Adding an object to a ModelAndView in a Spring controller after forcing a download does not seem to work.
Code at Controller method
ModelAndView view = new ModelAndView("");
view.setViewName("pom-upload");
view.addObject("uploadStatus", "Uploaded pom has been successfully processed!");
response.setHeader("Content-Disposition", "attachment; filename=pom.xml");
IOUtils.copy(inputStreamToDownload, response.getOutputStream());
response.flushBuffer();
return view;
I get the file downloaded successfully.
But when I try to access the "uploadStatus" message in my JSP like
<c:out value="${uploadStatus}"></c:out>
or
div id="status-message" class="alert alert-success" role="alert">${uploadStatus}</div>
I do not get the message from ${uploadStatus}
What could the reason be and how would I fix this?
Ok, it sounds like you want to display a message to the user after they have downloaded a file. A couple options.
User clicks download link. This goes to success page. Success page uses Refresh header or javascript to initiate download. So success comes a little early.
See Detect when browser receives file download for some ideas on detecting when the browser gets the download.

Localhost returns 404.3 when fetching json through ajax (Windows 8.1)

So I have been getting the infamous 404.3 error when trying to use AXAJ to access a .json file launching the site (or more of a test app hehe) through WebMatrix on localhost.
Yes, I am aware of the IIS configuration. I am on Windows 8.1(x64), so I had to even turn on MIME types functionality separately. I configured a MIME type for .json with application/javascript. Then I went and added a handler to *.json, pointed it to C:\WINDOWS\system32\inetsrv\asp.dll. I set the verbs to GET and POST (those are what I use in my ajax function). I also tried unchecking the "Invoke the handler only if request is mapped to..." to no avail.
I am using one function to send data to PHP file which writes it to the JSON file and then another to fetch data from the JSON file directly. Writing through PHP works. Fetching doesn't. I am completely at a loss, does anyone have any ideas? The code I am using to fetch the data is your bog-standard ajax:
function getDate(path, callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
var data = JSON.parse(httpRequest.responseText);
if (callback) callback(data);
}
}
};
httpRequest.open('GET', path);
httpRequest.send();
}
When I host this on my server space, it works totally fine. But I want to get it to work locally for testing purposes as well.
If writing to the file works but fetching doesn't work. Then you should check for the link of the file.
The error 404 as the name refers to, is an error for the file name. There isn't any other sort of error, even the Ajax request is working fine and giving the error 404 (file not found). So the only thing that you can do is, to make sure that while fetching the data, you use the correct link.
Here can be a help, when you send the Request through Ajax, there is a Network tab in your Browser's console. Open it, and look for the request. It would in red color denoting an error and click it. You'll see that the link you're providing isn't valid.
Look for the errors in the File Link then and update it.
The lengths I go to, to clean up my profile...
When you require a JSON format, or any file for that matter you have to specify in your request what data type you need, IIS will not make any assumptions. So
xhr.setRequestProperty('Content-Type', 'application/json');
is something one must not forget. I set also the X-Requested-With header. Note that to reproduce this issue I used IIS that is installed on Windows 10 Pro, so not exactly the same system (3 years later - holy crap!).

What is difference between Response.Redirect("http://url") and Response.Write("REDIRECT=http://url")?

I'm working on ASP.NET MVC3 with C#.
What is difference between Response.Redirect("http://www.google.com"); and Response.Write("REDIRECT=http://www.google.com");?
The difference is that the first will replace the response with a redirection page and end the execution, while the second will just write the text to the response stream and continue with creating the rest of the page.
Response.Redirect() sets an HTTP 302 header along with the URL to be redirected to.
Response.Write("REDIRECT=http://www.google.com"); will write that string to the response body, as in that redirect text would be appended to the HTML of your web page.
This will create the correct full HTTP Header for you:
Response.Redirect("http://www.google.com");
You have the ability to set or change some paramters for the HTTP Header.
HttpResponse Class
e.g set HTTP Status Code 404 or 500 or in your case 302 for redirect.
e.g set the HTTP Mime-type for jpg
Will write into the Body in your response..like a string output
Response.Write("REDIRECT=http://www.google.com");
The methods in question are quite self explanatory :)
Response.Redirect("http://www.google.com");
The Redirect will redirect you to another page, in the case it will take you to Google's home page.
Response.Write("REDIRECT=http://www.google.com");
The Write method will write a string of text to the web page. In this case it will write the text "REDIRECT=http://www.google.com" to your web page.
Play around with these 2 methods in your web project and see what happens.

Error using Json-feed for login: ACS50011

I have an RP for which I've built a login page using the Json feed from ACS. The IP images are linked to the .LoginUrl attribute of the feed and when I click on one of the images it correctly jumps to that IP's page.
Entering my credentials, however, I'm redirected to a page on the appfabriclabs.com site with the following error:
HTTP Error Code: 400
Message: ACS50000: There was an error issuing a token.
ACS50011: The RP ReplyTo address is missing. Either the RP ReplyToAddresses
are not configured or an invalid wreply 'https://www.skillscore.it/' was received
in the sign-in request.
the RP is configured in the App Labs site with a returnUrl of:
https://www.skillscore.it/Home/FederationResult
and in looking at the wreply parameter in the feed, I see:
https%3a%2f%2fskillscore.accesscontrol.appfabriclabs.com%3a443%2fv2%2fwsfederation
According to some SO articles like [this one] the return url of the app should be a prefix of the wreply parameter - which is clearly not the case here.
so... what have I done wrong now?
e
p.s. one interesting bit of info: in the Application Integration page of ACS there is a link to the ACS-hosted login page. the link used there seems to differ from the one I'm given in the feed; in particular, the ACS-hosted page uses a wctx of:
pr%3dwsfederation%26rm%3dhttps%253a%252f%252fwww.skillscore.it%252f
whereas the feed gives me:
pr%3dwsfederation%26rm%3dhttps%253a%252f%252fwww.skillscore.it%252f%26ry%3dhttps%253a%252f%252fwww.skillscore.it%252f
so I don't know what that's worth but maybe it's a clue to what's wrong.
* update *
decoded, that last string is:
pr=wsfederation
&rm=https%3a%2f%2fwww.skillscore.it%2f
&ry=https%3a%2f%2fwww.skillscore.it%2f
which clearly shows the Json feed is providing an ry that is not present in the ACS-hosted page... meaning anything to anyone?
ok. my bad. apparently, when I was fetching the Json feed, the URL I used did not have the reply_to set correctly.

Problem sending AJAX request with headers on Blackberry Webworks

I am developing a Blackberry webworks application and I am having trouble with an AJAX request that I am making to a server. I am learning HTML/Javascript/AJAX on the fly, so excuse any beginner mistakes. Basically, formatted HTTP requests are made to the server, which returns JSON objects that I use in the application. I am using AJAX to make the requests without any kind of framework.
Most requests do not have to be authenticated, and those are returning just fine. However, to access a directory part of the server, a username and password are encoded and sent as a header with the XMLHTTPRequest. when I try and add the header, the request is sent, but I never get anything back. The readyState property is set to 1, but never goes beyond that. I know the server works fine, because I did the same thing for iPhone, and it worked.
Here is the relevant code:
function grabFromServer(httpRequest){
httpConnection = new XMLHttpRequest();
var me = this;
httpConnection.onreadystatechange=function(){
alert(httpConnection.readyState);
if(httpConnection.readyState==4){
me.processResponseText(httpConnection.responseText);
}
};
httpConnection.open("GET", httpRequest,true);
if(this.request == "company" || this.request == "property" || this.request == "individual"){
var authorized = this.checkCredentials();
if(!authorized){
//ask for username pword
}
//here, add credentials
httpConnection.setRequestHeader("Authorization", "Basic : ODI5ZGV2bDokY19kdXN0Ym93bA==");
}
httpConnection.send();
}
Your code appears to be good. Have you added an entry in your config.xml file to allow access to your domain? You should see an entry for something like <access subdomains="false" uri="http://data.mycompany.com/"/>. To make any HTTPRequests to an external website from a WebWorks application, you have to add an entry to "whitelist" domain like this.
If you're using the eclipse plugin, open up the config.xml file, click the Permissions tab at the bottom, and click "Add Domain".

Resources