Page:
<a href="servlet/Download" >下载</a>
Java code:
Public class Download extends httpservlet { Public Download() {Super(); } Public void Destroy() {Super. Destroy ();//Just puts "destroy" string in log //Put your code here} Public void Doget(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException { This. DoPost (Request, response); } Public void DoPost(HttpServletRequest request, httpservletresponse response)throwsServletexception, IOException {String path ="d:/upload/hahaha.";Try{//path refers to the file that you want to download. File File =NewFile (path);//Get the file name. String filename = File.getname ();//Get the suffix name of the file. String ext = filename.substring (Filename.lastindexof (".") +1). toUpperCase ();//Download the file in the form of a stream. InputStream FIS =NewBufferedinputstream (NewFileInputStream (path));byte[] buffer =New byte[Fis.available ()]; Fis.read (buffer); Fis.close ();//Empty responseResponse.reset ();//Set the header of responseResponse.AddHeader ("Content-disposition","Attachment;filename="+NewString (Filename.getbytes ("gb2312"),"Iso8859-1")); Response.AddHeader ("Content-length",""+ file.length ()); OutputStream toclient =NewBufferedoutputstream (Response.getoutputstream ()); Response.setcontenttype ("Application/octet-stream"); Toclient.write (buffer); Toclient.flush (); Toclient.close (); }Catch(IOException ex) {Ex.printstacktrace (); } } Public void Init()throwsservletexception {//Put your code here}}
This download can only be downloaded from files on the program's local disk. If you want to download a file from a server (for example, by uploading to a Tomcat server), see my other blog post:
Upload and download using Jspsmartupload
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JSP file Download (Do not use jar package)