Java Tips: How to open a non-HTML file from servlet

zhaozj2021-02-17  74

1, summary

The Java Servlet program provides a simple way to send an HTML file to the client browser. However, some sites now offer some non-HTML access files such as Adobe PDF, Microsoft Word, and Microsoft Excel files. This article explains how to use PDF and Word as an example of how to send a non-HTML file to the client browser from servlet. In fact, through this article, you can send any format files through the MIME type. At the same time, you can also understand how to interact with the firewall through servlet.

Open a file through a servlet, you only need to simply add this file to the servlet's output stream. Although you look very simple, you have to need some things, such as binary files and multiple files when you open a non-HTML file.

You can get a servlet output stream in a way.

ServletOutputStream out = res. maxOutputStream ();

The Internet sends multiple, multimedia and binary files through the MIME (Multi-Used Network Mail Extension) protocol. In the Servlet's Response object, setting the MIME type of the file you want to open is very important.

2, MIME type

The client browser identifies non-HTML files and decides what package containers to render this data file via the MIME type. The plugin can decide to open these files through the MIME type. When we download these files, we can browse these files through your browser.

MIME type is useful, they allow the browser to handle different file types through the built-in technology.

The MIME type is "Application / PDF" for a PDF file. When you open a PDF file in Servlet, you must set "Application / PDF" in front of Response:

// mime type for pdf doc res. setcontentType ("Application / PDF");

Open a Word document, you should be set to "Application / Msword":

// mime type for msword doc res. setcontentType ("Application / Msword");

For Excel documents, use the MIME type is "Application / VND.MS-Excel". If the plugin system required is not installed, the browser will appear a prompt box, ask the user whether it is turned on or saved on the current location.

3, content deployment

The HTTP response header of the deployment content allows the servlet to specify information about the file type. With this header, you can make a specific way to open this file (not only in your browser), and it should not display automatically. You can set the name you want to save. This file should be the file name displayed in the dialog. If you don't want to specify a file name, you get the name of the file you have the same name.

In servlet, you can set your head like the code below.

Res.SetHeader ("Content-Disposition", "Attachment; FileName =" "EXAMPLE.PDF"); // attachment - Since We don't want to open // it in the browser, but // with adobe Acrobat, And set the // default file name to us.

If you want to open a Word file, you should do it as follows: res.sethead, "attachment; filename" "example.doc");

4, package

The rest of the work is very simple. You need to create a java.net.URL object based on the name of the file you want to open. This string should completely indicate the location of this file. for example:

String fileurl = http://www.adobe.com/aboutadobe/careeropp/pdfs/adobeapp.pdf;

Your URL string should be like http://www.gr.com/pub/somefile.doc or

Http://www.gr.com/pub/somefile.xls this look.

But you must confirm that the file you open is consistent with the file type specified in your MIME type.

URL URL = New URL (fileURL);

5, firewall

If your browser needs to pass the firewall, the last thing is that you need to worry is your URL connection. You need to find some information about your proxy server, such as host names and port numbers to connect with the firewall. If you use Java 2, you should create a URL connection object, set the following system properties:

URLConnection conn = url.openConnection (); // Use the username and password you use to // connect to the outside world // if your proxy server requires authentication String authentication = "Basic" newsun.misc.BASE64Encoder ().. Encode ("UserName: Password"; System.getProperties (); put ("proxyset", "true"); system.getproperties (). Put ("proxyhost", proxy_host; // Your proxy host System.getProperties (). Put ("proxyport", proxy_port); // Your proxy port conn.setRequestProperty ("proxy-authorization", authentication;

If you use JDK 1.1, you can build system properties. You should create a java.net.URL object with your proxy server information.

URL = New URL ("http", proxy_host, integer.parseint (proxy_port), fileurl; // Assumes Authentication is not Required

6, realize

When you start reading your file, you need to include InputStream from the UrlConnection (OR URL) object.

In the following example, you use a bufferedInputStream to limit this InputStream.

If you are using this urlConnection, the following is this code:

BufferedinputStream Bis = New BufferedInputStream (Conn.getInputStream ()); if you are using the URL, it is like the following code:

BufferedInputStream Bis = New BufferedInputStream (Url.OpenStream ());

Once you have finished working, you only need to write every byte from the input stream to the output stream of the servlet.

BufferedoutputStream Bos = New BufferedoutputStream (OUT); Byte [] Buff = New Byte [2048]; int BytesRead; // Simple read / write loop. While (-1! = (BYTESREAD = BIS.READ (buff, 0, buff. Length)))) {bos.write (buff, 0, bytesread);

Finally, close this stream in the final module.

This example implements this function by using a servlet's dopost method.

Public void dopost (httpservletRequest Req, httpservletResponse res) throws servletexception, ioException {servletoutputstream out = res. maxOutputStream (); // ------------------------ --------------------------------------- // set the output data's mime type // -------------------------------------------------- ------------ Res.SetContentType ("Application / PDF"); // Mime Type for PDF DOC / / ------------------ --------------------------------------------- // Create An Input Stream from fileurl // ------------------------------------------- ------------------ String fileurl = "http://www.adobe.com/aboutadobe/careeropp/pdfs/adobeApp.pdf";//----- -------------------------------------------------- ----- // Content-Disposition Header - Don't open in browser and // set the "save as ..." filename.// * there is reportedly a bug in IE4.0 Which Ignores this ... / / -------------------------------------------------------------------------------------------- ------------ Res.SetHeader ("Content-Disposi TION, "attachment; filename =" = "example.pdf"); // -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ----------------------------------- // proxy_host and proxy_port shop be your proxy host and port // That Will Let you go through the firewall welch automation.// Otherwise set the system protes and use urlConnection.getinputStream () .//----------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- NULL; try {url url = new url ("http", proxy_host, integer.parseint (proxy_port), fileurl;

// Use Buffered Stream for reading / writing bis = new BufferedInputStream (url.openStream ());. Bos = new BufferedOutputStream (out); byte [] buff = new byte [2048]; int bytesRead; // Simple read / write Loop. While (-1! = (BytesRead = Bis.Read (buff, 0, buff.length)) {bos.write (buff, 0, bytesread);}} catch (final malformedurlexce) {system.out. Println ("Malformedurlexception."); Throw E; Final IOException E) {System.out.Println ("IOException."); throw E;} finally {if (bis! = null) bis.close (); IF (bos! = null) bos.close ();}} 7, summary

As you can see, open a non-HTML in a servlet is very simple, even outside a firewall. You can use the same code to open image files or other types of multimedia files, just set up the MIME type correctly. Today, more information on the Internet has become valid, and a lot of information is stored in non-HTML types. In contrast, developing a servlet is a non-HTML document is an easy and convenient way to provide more information to your users.

转载请注明原文地址:https://www.9cbs.com/read-31174.html

New Post(0)