I want to show the file content in new tab in browser. What i have done is this:
int BUFF_SIZE = 102400;
FileInputStream is = null;
byte[] buffer = new byte[BUFF_SIZE];
int a = -1;
try
{
is = new FileInputStream(file);
ByteArrayOutputStream out = new ByteArrayOutputStream();
while((a = is.read(buffer)) != -1)
{
out.write(buffer);
}
out.flush();
out.close();
ServletOutputStream os = null;
os = response.getOutputStream();
os.write(out.toByteArray());
os.close();
is.close();
}
catch(Exception e)
{
// Exception handling
}
But this is leading to download of the file instead of opening the file-content in new tab.
I am not able to find what i am doing wrong.
Any help would be great!!
Actually, all you should need to do now is add JQuery to your webpage, and use JQUery.get. Once you get the html from the servlet, use jquery or javascript to set the text in your tab.
BTW, you might want to set other details on the servlet output stream, like file type, length etc. Just a thought
You could also try this with the omnifaces library
Faces.sendFile(file, false);//true makes it as an attachment
more information on http://omnifaces.org/docs/javadoc/1.8/org/omnifaces/util/Faces.html#sendFile(java.io.File,%20boolean)
A web application might not even know what is a brower. It receives requests through HTTP protocol and send responses through same protocol. The protocol by itsels knows nothing about browsers and tabs.
You must use javascript for anything that happens at browser level. Other answers adviced you to use jQuery. It is a well known javascript library that hides differences between browsers, but there are others around (dojo, extJs, ...) : Google and make your choice.
By the way, if all you want is open an URL in a new tab, that's one of the very few operations that you can do at HTML level. Just look at this example
from W3Schools.com :
Visit W3Schools!
that opens www.w3schools.com in a new tab (if browser has tabs what is now common) or a new window.
Related
I'm working on a Spring Boot project and I need users to be able to send a GET request to my service and get multiple files as response without pages involved. This is what I have right now:
public void get(HttpServletResponse response,FileInputStream[] streams){
String boundary = "------customBoundary";
response.setContentType("multipart/mixed; boundary="+boundary);
String contentType = "Content-type: audio/mpeg";
var outputStream = response.getOutputStream();
for(FileInputStream ois:streams){
if(ois!=null){
outputStream.println("--"+boundary);
outputStream.println(contentType);
outputStream.println("Content-disposition: attachment; filename=\"random.mp3\"");
outputStream.println();
try{
BufferedInputStream inputStream = new BufferedInputStream(ois);
int swap;
while ((swap = inputStream.read()) != -1) {
outputStream.write(swap);
}
outputStream.println();
outputStream.flush();
ois.close();
inputStream.close();
}catch (Exception s){
s.printStackTrace();
}
}
}
outputStream.println("--"+boundary+"--");
outputStream.flush();
outputStream.close();
}
If you access the service on Chrome, it'll automatically download a file name "download", as the browser sees the whole this as one giant file attachment.
I think the problem may be at the ContentType part, so far I tried "multipart/x-mixed-replace" as some post here suggested, only to find out later that it was removed several years ago. I tried "multipart/form-data" out of desperation and that didn't work.
The files I'm dealing with are media files, it's quite large and I'm running this on a crappy server, so putting them in one zip file is not an option.
Most of the result I found more or less have something to do with html or javascript, but what I'm doing here is intended as an API for other services to call so I'm hoping it can be done with pure java.
I have a JSP page that displays a PDF document when it is called. Assuming I generate the URL in this format:
http://localhost:8080/repository/file/view/viewPDF.jsp?fileID=27455
and send it to another user. The user can view the document (id:27455) on his browser with no problem. But let's say I want to hide the PDF toolbar shown so user is not allowed to access that toolbar.
I found that by entering this link:
http://localhost:8080/repository/file/view/viewPDF.jsp?fileID=27455#toolbar=0
Then this above will hide the toolbar but it's vulnerable since the other user can change it's value to 1 and the toolbar appears. I am thinking if it's possible to hide it internally in back end code instead but couldn't figure out how.
My viewPDF.jsp:
<%#page import="java.io.*"%>
<%#include file="../../../WEB-INF/jspf/mcre.jspf" %>
<%
response.setContentType("application/pdf");
boolean debug = true;
try {
String snodeid = request.getParameter("nodeID");
long nodeid = Long.parseLong(snodeid);
Pdfinfo pdf = PPFacade.getPDFInfo(nodeid);
String pdfpath = pdf.getFfullpath();
if (debug) {
System.out.println("=============== PDF STREAM ================");
System.out.println("pdfpath = "+ pdfpath);
}
//int len = (int)new File("D://test.pdf").length();
int len = (int)new File(pdfpath).length();
response.setContentLength(len);
byte[] buf = new byte[len];
FileInputStream pdfin = new FileInputStream(pdfpath);
pdfin.read(buf);
pdfin.close();
OutputStream pdfout = response.getOutputStream();
pdfout.write(buf,0,len);
pdfout.flush();
if (debug) {
System.out.println("=============== END PDF STREAM ================");
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
%>
<head>
PDF
</head>
Of course I know hiding #toolbar is not foolproof since any user with such knowledge can easily bypass it.
As the toolbar is a function of the browser, not the server or the pdf file, there's no way to force it to be shown or not without notifying the browser in some way.
And anyone intercepting the information that goes to the browser can indeed modify that information.
Of course even were you able to prevent that, they could always download the PDF to their file system and open it using any tool that allows reading PDFs, including such tools as they can create themselves.
So no, you can't lock down such things. And why would you even want to?
Closest you could come is embedding the PDF in a div that loads the PDF viewer browser plugin and uses an AJAX request to the server to retrieve the PDF content. But even then someone can intercept the request to the server and replicate that request using say curl and download the stream to a file directly.
I have a link to a PDF and when I click on it I want it to open a new tab and render in the new tab as opposed to asking me to download it. How do I do that?
note, I'm asking this question so I can answer it. This information can be pieced together from other answers, but I'd like it to be all in one place
To open a link in a new tab (PDF or not) you must modify the HTML of that link from
PDF
to
PDF
To open a PDF in the browser you must make a server side change to the response header. In Java, you would do this:
response.setContentType("application/pdf");
response.addHeader("content-disposition", "inline; filename=link_to_pdf.pdf");
Of key importance is the inline. If you put attachment, your browser will try to download it instead. You can read more here.
The secret is using InputStreamResource in method response instead as ResponseEntity:
#GetMapping(path = "/pdf/{key}", produces = MediaType.APPLICATION_PDF_VALUE)
#ResponseBody
public InputStreamResource pdf(#PathVariable("key") String key){
InputStream file = pdfservice.get(key);
return new InputStreamResource(file);
}
I want to have an application which parses various RSS feeds and send the information to a remote server. The information is sent in xml format via http. At first I tried to deploy this application on my own server, so I send the xml using the method shown in this tutorial by Java Tips. Here is my code which is replicated from the example:
First Method
String strURL = "http://localhost/readme/readme_xml";
String strXMLFilename = "output.xml";
File input = new File(strXMLFilename);
PostMethod post = new PostMethod(strURL);
post.setRequestEntity(new InputStreamRequestEntity(
new FileInputStream(input), input.length()));
post.setRequestHeader(
"Content-type", "text/xml; charset=ISO-8859-1");
HttpClient httpclient = new HttpClient();
try {
int result = httpclient.executeMethod(post);
System.out.println("Response status code: " + result);
System.out.println("Response body: ");
System.out.println(post.getResponseBodyAsString());
} finally {
post.releaseConnection();
}
This works perfectly (I even tested using a remote server outside the localhost). Then, somehow I cant use my own server to deploy this application, so I decided to migrate to Google Apps Engine. One thing about it, as we know it, is that not all libraries are allowed in the environment. So I try another method shown in ExampleDepot.com (I can't find where the exact url though) as below:
Second Method
try {
/* fill up this url with the remote server url */
URL url = new URL("http://localhost/readme/readme_xml");
FileReader fr = new FileReader("output.xml");
char[] buffer = new char[1024*10];
int len = 0;
if ((len = fr.read(buffer)) != -1){
/* send http request to remote server */
URLConnection conn = url.openConnection();
conn.setRequestProperty("Content-Type","text/xml;charset=ISO-8859-1"); /* need to specify the content type */
conn.setDoOutput(true);
conn.setDoOutput(true);
PrintWriter pw = new PrintWriter(conn.getOutputStream());
pw.write(buffer, 0, len);
pw.flush();
/* receive response from remote server*/
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String input = null;
while ((input = bf.readLine()) != null){
System.out.println(input);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
The second method though, doesn't work and gives the following error (I use SimpleXMLElement (php) object to parse xml in the remote hosting):
Error message from remote server
Here's the php code from the remote server (In here, I just want the SimpleXMLElement to parse the xml without doing anything else fancy for now)
$xml = new SimpleXMLElement('php://input', NULL, TRUE);
foreach ($xml -> attributes() as $name => $val){
echo "[".$name."] = ".$val."\n";
}
I thought the cause of this problem is the malfunction xml file (because the eclipse IDE indicates there's error of "invalid byte 1 of 1-byte utf-8 sequence"). Then I use the same exact input xml file to the first method, but it still works perfectly.
So is there any adjustment that I need to make to the second method? Or is there any other method that I can use to send xml file to remote server? Let me know if I need to add some other details. Thanks for your help.
NOTE: I actually solved this problem by using the solution given in the comments. I didn't use approaches suggested in the answers, even though those answers are pretty useful. So, I didn't select the best answer out of those answers given. Nonetheless, I still appreciate all of your helps, thus deserve my upvote. Cheers!
I guess you need to change the content type to multipart/form-data. See an already answered question in detailed. The file upload is discussed at the bottom of this example
I would, as the first answer suggest, read the file with an InputStream. Converting from byte to char and back again is unnecessary and a source of error. Also, verify that the input file really is using the ISO-8859-1 encoding.
UPDATE:
When using a FileReader, you accept the default encoding (i.e. how to make chars from bytes). This encoding must match the encoding used for the input file, otherwise there's a great risk that the result is corrupted. The default Java encoding is different for different platforms, so it is generally not a good idea to rely on it.
In your second example, there's no reason to read the file as characters, since it will be sent on the wire as bytes anyway. Using byte streams all the way also avoids the encoding issue (apart from the information in the content-type header).
never read a file as chars unless you are reading a text file. xml is not text, it is a binary format. copy the file using normal InputStreams and byte[]s.
also, as #beny23 suggested in his comment, make sure you always copy streams using a loop, not a single read() (even if your buffer is big enough, it is not guaranteed that the InputStream will give you all the bytes in one call, even for a FileInputStream).
In my application, I want show a printable PDF acrobat file with in the browser or outside the browser other than saving. In Firefox by default it will ask for save or open, I don't need that dialogue. I want to show that file preferably outside the browser. Can you please suggest me.
Thanks,
Vara Kumar.PJD
You can suggest to the browser that it should show the PDF in a window rather than offering to download it via the Content-Disposition header:
response.addHeader("Content-Disposition", "inline");
The "inline" value suggests that the content be rendered inline (as opposed to the "attachment" value suggesting the browser offer to download it).
Once you've made the suggestion to the browser, the browser may or may not accept your suggestion, depending on its implementation and possibly its user preferences.
I don't think this is something you can control from your app, i think this is the matter of environment/browser/plugins that users are using... but zou can open new window for your pdf by javascript like this link
You can do like some thing like this.
response.setContentType("application/pdf");
InputStream in = new FileInputStream("answerconnect.pdf");
OutputStream out = response.getOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();