Servlet implements file download, servlet implements file
(1) The main directory of the project is as follows: (demonstrate the location of the image and servlet)
(2) The specific implementation code is as follows:
Package com. lc. httpTest; import java. io. fileInputStream; import java. io. IOException; import java. io. outputStream; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class xiazaiwenjian extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setContentType ("text/html"); // demonstrate how to download the file response. setHeader ("Content-Disposition", "attachment?filename=1.jpg "); // open the file web site to download the file first read the file into the servlet's memory and send the file to the browser segment // The Ghost stream can only send text byte streams to send the file // 1 get the file to download file full path String path = this. getServletContext (). getRealPath ("/images/1.jpg"); // 2 create a File Transfer Stream FileInputStream FD = new FileInputStream (path ); // make a buffer byte array byte buff [] = new byte [1024]; int len = 0; // the actual number of bytes read each time OutputStream OS = response. getOutputStream (); while (len = Fi. read (buff)> 0) {OS. write (buff, 0, len);} // close the OS. close (); FCM. close ();} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doGet (request, response );}}
Encoding of Servlet file downloads
The possible problem here is that the page code is not gb2312. You can pay attention to this content when writing the Page code:
<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Title>... </title>
....
</Head>
<Body>
....
</Body>
</Html>
Servlet File Download
Content-type:
Tool.oschina.net/commons