In Java Web, the response in the servlet downloads the image, javawebservlet
Package org. servlet. demo;
Import java. io. File;
Import java. io. FileInputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java. io. OutputStream;
Import java.net. URL;
Import java.net. URLEncoder;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
/**
* Send a request to download the image in the servlet.
*
* @ Author k. sea
*
*/
Public class DownLoadImageServlet extends HttpServlet {
@ Override
Protected void doGet (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
// Obtain the image path of the current directory
// String path = this. getServletContext (). getRealPath ("/image/tuxing.png ");
String path = this. getServletContext (). getRealPath ("/image/ .png ");
// Get the file name
String fileName = path. substring (path. lastIndexOf ("\") + 1 );
System. out. println (fileName );
// Specify the browser Header
// English is correct during the download.
// Resp. setHeader ("content-disposition", "attachment; fileName =" + fileName );
// Set transcoding if the image name is Chinese
Resp. setHeader ("content-disposition", "attachment; fileName =" + URLEncoder. encode (fileName, "UTF-8 "));
InputStream reader = null;
OutputStream out = null;
Byte [] bytes = new byte [1, 1024];
Int len = 0;
Try {
// Read the file
Reader = new FileInputStream (path );
// Write the output stream of the browser
Out = resp. getOutputStream ();
While (len = reader. read (bytes)> 0 ){
Out. write (bytes, 0, len );
}
} Catch (Exception e ){
// TODO Auto-generated catch block
E. printStackTrace ();
} Finally {
If (reader! = Null ){
Reader. close ();
}
If (out! = Null)
Out. close ();
}
}
@ Override
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
// TODO Auto-generated method stub
DoGet (req, resp );
}
}