The data in the request code and the response code can only be in the English state, that is, iso8859-1, cannot be Chinese, so if the name of the file is Chinese, URL encoding is required
This is to tell the browser to download the way, the data sent to be URL-encoded, the name of the file URL---Encoding principle:
Convert beauty to Utf-8 form then convert to 16 binary, front plus% utf-8 a kanji three bytes below just assume
Mei 1100 1001 1110 0110-0001-->%2a%3d%4e
Female 1110 1011 1111 0110 1111 0001-->%2b%3d%6c
The browser will decode the URL directly by default
Response.setheader ("Content-disposition", "Attachment;filename=" +urlencoder.encode ("beauty. jpg", "utf-8"));
Package Cn.itheima.response;import Java.io.fileinputstream;import Java.io.ioexception;import java.io.InputStream; Import Java.io.outputstream;import Java.net.urlencoder;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;//Browser Default is to open the file directly public class Downloadservlet extends HttpServlet {public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// This is to tell the browser to download the way, the data sent to be URL-encoded, the name of the file URL----Encoding principle://The beautiful woman into the form of utf-8 and then converted to 16 binary, the front plus% utf-8 a kanji three bytes below the only hypothesis//beauty 1100 1001 1110 0110 + 0001-->%2a%3d%4e//female 1110 1011 1111 0110 1111 0001-->%2b%3d%6c//The browser will decode the URL directly by default res Ponse.setheader ("Content-disposition", "Attachment;filename=" +urlencoder.encode ("beauty. jpg", "utf-8"));// A byte input stream is required InputStream in=new FileInputStream (This.getservletcontext (). Getrealpath ("beauty. jpg"));//byte output stream OutputStream Out=response.getoutputstream (); byte b[]=new byte[1024];int Len=0;while ((Len=in.read (b))!=-1) {out.write (b, 0, Len);} In.close ();} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}
Operation Result:
Dark Horse day03 File Download & Chinese garbled principle and URL encoding