Download Download the code for an Excel template

Source: Internet
Author: User


<%--
Code to download the file directly in the JSP page (change the Servlet or
JavaBean words to change their own), support the Chinese language attachment name (do the transfer inside code processing). In fact, just to
The out output byte is considered to be an attachment, not necessarily to read the original data from the file, from the data
can also be read in the library.
Three parameters required Newname,name,path
--%>
<%@ page contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%>
<%@ page import= "java.io.*,java.util.*,java.text.*"%>

<%!//if returns True, then should return a 304 (http_not_modified)
public static Boolean checkFor304 (httpservletrequest req, file file) {
We ' ll do some handling for CONDITIONAL GET (and return a 304)
If the client has a set of the following headers, do not try for a 304.
Pragma:no-cache
Cache-control:no-cache
if ("No-cache". Equalsignorecase (Req.getheader ("Pragma"))
|| "No-cache". Equalsignorecase (Req.getheader ("Cache-control")) {
Wants specifically a fresh copy
} else {
HTTP 1.1 etags Go first
String Thistag = long.tostring (file.lastmodified ());
String ETag = Req.getheader ("If-none-match");
if (ETag! = null) {
if (Etag.equals (Thistag)) {
return true;
}
}
Next, try If-modified-since
DateFormat Rfcdateformat = new SimpleDateFormat ("EEE, dd MMM yyyy HH:mm:ss z");
Date lastmodified = new Date (file.lastmodified ());
try {
Long ifmodifiedsince = Req.getdateheader ("if-modified-since");
Log.info ("ifmodifiedsince:" +ifmodifiedsince);
if (ifmodifiedsince! =-1) {
Long lastmodifiedtime = Lastmodified.gettime ();
Log.info ("Lastmodifiedtime:" + lastmodifiedtime);
if (lastmodifiedtime <= ifmodifiedsince) {
return true;
}
} else {
try {
String s = Req.getheader ("if-modified-since");
if (s! = null) {
Date ifmodifiedsincedate = Rfcdateformat.parse (s);
Log.info ("ifmodifiedsincedate:" + ifmodifiedsincedate);
if (Lastmodified.before (ifmodifiedsincedate)) {
return true;
}
}
} catch (ParseException e) {
Log.warn (E.getlocalizedmessage (), E);
}
}
} catch (IllegalArgumentException e) {
Illegal date/time header format.
We fail quietly, and return false.
Fixme:should really move to Etags.
}
}
return false;
}%>
<%
String filename= "Appmappingtemplate.xlsx";
String Filepath= (String) request.getattribute ("FilePath");
Get the path to the template file
String FilePath = Request.getsession (). Getservletcontext (). Getrealpath ("/");
FilePath + = "pages//xflow//appmappingtemplate.xlsx";

System.out.println ("filepath:" + filepath);
Boolean isinline = false; Allow to open directly inside the browser (if the browser is able to preview the contents of this file,
Then the file will be opened, otherwise you will be prompted to download)
Empties the buffer, prevents blank lines in the page, and adds spaces to the file content to be downloaded
If not emptied, Tomcat will error when calling Response.reset ().
Java.lang.IllegalStateException:getOutputStream () have already been called for
This response,
Out.clear ();
{{{} BEA Weblogic must read
Fixed issue where Bea Weblogic appeared "Getoutputstream () has already been called for this response" error
File stream output is processed when downloading files:
Add Response.reset () and do not wrap all the%>, including the last one;
Because application server handles compiling the JSP, the content between%> and <% is generally output as is, and the default is PrintWriter,
And you're going to stream output: Servletoutputstream, which is equivalent to trying to use two output mechanisms in the servlet,
Will occur: Getoutputstream () has already been called for this response error
See the second section of the "more Java pitfill" Web Layer Item 33: Trying to use two output mechanisms in a servlet 270
And if there is a line break, there is no problem with the text file, but for other formats, such as AutoCAD, Word, Excel, and other files
The downloaded file will have some more line breaks 0x0d and 0x0a, which may cause some format files to not open, some can open normally.
This also allows the buffer to be emptied, preventing empty lines in the page from being exported to the downloaded content.
Response.reset ();
// }}}
try {
Java.io.File f = new Java.io.File (FilePath);
if (!f.exists ()) {
System.out.println ("The file is not exist!");
Return
}
if (f.exists () && f.canread ()) {
We want to check whether the client has the latest version of this file in the cache and tell
The client does not have to re-download, of course, if you do not want to check
if (checkFor304 (request, F)) {
The client already has the latest version and returns 304
Response.senderror (httpservletresponse.sc_not_modified);
Return
}
From the server's configuration to read the file's ContentType and set this contentType, it is not recommended to set the
Application/x-download, because sometimes our customers might want to open it directly in the browser,
such as Excel reports, and Application/x-download is not a standard MIME type,
FireFox doesn't seem to know the MIME type of this format
String mimetype = null;
MimeType = Application.getmimetype (FilePath);
if (mimetype = = null) {
MimeType = "Application/octet-stream;charset=utf-8";
}
Response.setcontenttype (mimetype);
IE can only use IE to know the head to download HTML files, otherwise ie must open this file!
String ua = Request.getheader ("user-agent"); Get terminal type
if (UA = = null)
UA = "user-agent:mozilla/4.0 (compatible; MSIE 6.0;) ";
Boolean Isie = Ua.tolowercase (). IndexOf ("MSIE")! =-1; Whether it is IE
if (Isie &&!isinline) {
MimeType = "Application/x-msdownload";
}
Below we will try to let the client save the file when the correct file name is displayed, in particular, the file name
Convert to ISO8859-1 encoding
String downfilename = new String (F.getname (). GetBytes (), "UTF-8");
String Inlinetype = isinline? "Inline": "Attachment"; Whether inline attachments
Response.setheader ("Content-disposition", inlinetype+ "; filename=\" "+filename+" \ "");
Response.setcontentlength ((int) f.length ()); Set download content size
byte[] buffer = new byte[4096]; Buffer
Bufferedoutputstream output = null;
Bufferedinputstream input = null;
try {
Output = new Bufferedoutputstream (Response.getoutputstream ());
input = new Bufferedinputstream (new FileInputStream (f));
int n = (-1);
while ((n = input.read (buffer, 0, 4096)) >-1) {
Output.write (buffer, 0, N);
}
Response.flushbuffer ();
} catch (Exception e) {
}//The user may have canceled the download
finally {
if (input! = null)
Input.close ();
if (output! = NULL)
Output.close ();
}
}
Return
} catch (Exception ex) {
Ex.printstacktrace ();
}
If the download fails, tell the user that the file does not exist
Response.senderror (404);
%>

Download Download the code for an Excel template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.