<% -- Code for downloading files directly on the JSP page (modify Servlet or You can change the name of a JavaBean file by yourself. You can change the name of an attachment in Chinese (converted to an internal code). In fact, you only need The output byte is considered as the attachment content, and it is not necessary to read the original data from the file. The database can also be read. The newname, name, and path parameters must be input. -- %> <% @ Page contentType = "text/html; charset = utf-8" pageEncoding = "UTF-8" %> <% @ Page import = "java. io. *, java. util. *, java. text. *" %> <%! // If returns true, then shoshould 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 set the following headers, do not try to a 304. // Pragma: no-cache // Cache-control: no-cache If ("no-cache". Inclusignorecase (req. getHeader ("Pragma ")) | "No-cache". Inclusignorecase (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: shocould really move to ETags. } } Return false; } %> <% String newname = request. getParameter ("upfile_newname "); String name = request. getParameter ("upfile_name "); String path = request. getParameter ("upfile_path "); // String filePath = "c:/document .doc "; // If it is a relative path file under the web app, use the following code: If (path. charAt (0) = '/') path = path. substring (1 ); String filePath = application. getRealPath (path + "/" + newname ); Boolean isInline = false; // whether the file can be opened directly in the browser (if the browser can preview the file content, // The file will be opened; otherwise, a message will be prompted for download) // Clear the buffer to prevent empty lines on the page and add spaces to the file content to be downloaded // If it is not cleared, Tomcat will report an error when response. reset () is called. // Java. lang. IllegalStateException: getOutputStream () has already been called // This response, Out. clear (); // {BEA Weblogic required Read // Fixed the "getOutputStream () has already been called for this response" error in Bea Weblogic. // When downloading an object, use the file stream output method: // Add response. reset (), and do not wrap all %>, including the last one; // Because the content between %> and <% is usually output as is when the Application Server processes the jsp compilation, and the default value is PrintWriter, // You Need to output the stream: ServletOutputStream. This is equivalent to trying to use two output mechanisms in Servlet, // The following error occurs: getOutputStream () has already been called for this response. // For details, see the second part of "More Java Pitfill" Web layer Item 33: trying to use two output mechanisms in Servlet 270 // If there is a line feed, there is no problem with text files, but for other formats, such as AutoCAD, Word, Excel and other files // Some linefeeds 0x0d and 0x0a will be added to the downloaded file. This may cause some files in some formats to fail to be opened, and some files can be opened normally. // At the same time, this method can also clear the buffer to prevent empty rows on the page from being output to the downloaded content. Response. reset (); //}}} Try { Java. io. File f = new java. io. File (filePath ); If (f. exists () & f. canRead ()){ // Check whether the latest file version is available in the client cache. // The client does not need to be downloaded again. Of course, it does not matter if you do not want to check it. If (checkFor304 (request, f )){ // If the client has the latest version, 304 is returned. Response. sendError (HttpServletResponse. SC _NOT_MODIFIED ); Return; } // Read the contentType of the file from the server configuration and set this contentType. It is not recommended to set it // Application/x-download, because sometimes our customers may want to open it directly in the browser, // For example, Excel report, and application/x-download is not a standard mime type, // It seems that FireFox does not know this format of mime type String mimetype = null; Mimetype = application. getMimeType (filePath ); If (mimetype = null ){ Mimetype = "application/octet-stream; charsets = ISO8859-1 "; } Response. setContentType (mimetype ); // For IE, only HTML files can be downloaded using the header recognized by IE. Otherwise, IE must open this file! String ua = request. getHeader ("User-Agent"); // Obtain the 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 "; } // Next we will try to make the client display the correct file name when saving the file, specifically the file name // Convert to ISO8859-1 encoding String downFileName = new String (f. getName (). getBytes (), "ISO8859-1 "); String inlineType = isInline? "Inline": "attachment"; // whether to inline the attachment // Or using this, but this header might not supported by FireFox // Response. setContentType ("application/x-download "); Response. setHeader ("Content-Disposition", inlineType + "; filename =" "+ name + """); Response. setContentLength (int) f. length (); // you can specify the size of the downloaded content. 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 ); } <SPAN style = "COLOR: # ff00ff"> response. flushBuffer (); // understand how to download the content. </SPAN> } 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, the file does not exist. Response. sendError (404 ); %> |