An overview
1. What is file upload?
The process of saving a local file to a server is called a file upload.
2. What is file download?
broadly speaking, any process that obtains data from the server side is a file download, which is opened by the browser by default. Narrow file download refers to the data obtained from the server side is saved as an attachment to the local. So when downloading a file, you need to reset how the browser handles the response content:
Response.setheader ("Content-disposition", "attachment;filename=xxxxxx");
Because the response header only supports ISO-8859-1 encoding, if the file name contains Chinese, garbled characters will appear, so the file name must be converted to ISO-8859-1 encoding:
byte [] Buf=filenamestr.getbytes ("UTF-8"); // Convert the file name to the bytecode under the UTF-8 encoding system (working space with UTF-8 encoding) =new String (buf, "iso-8859-1"); // re-encode bytecode using iso-8859-1
The core code for file download in two Servlets
protected voiddoget (httpservletrequest request, httpservletresponse response)2throwsservletexception, IOException {3//TODO auto-generated Method Stub4 Response.setcontenttype ("Text/html;charset=utf-8");//set how content in the response body is encoded5 6/*7 * Convert the file name containing Chinese into ISO-8859-1 encoded Form 8*/9 String filenamestr = "Picture A";10byte[] bytes = Filenamestr.getbytes ("UTF-8");One String filename =NewString (Bytes, "Iso-8859-1");System.out.println ("filename=" +filename);System.out.println ("Start File Download");15 16//set the browser to handle responses as attachmentsResponse.setheader ("Content-disposition", "attachment;filename=" + filename + ". jpg");InputStream is = Getservletcontext (). getResourceAsStream ("/files/a.jpg");//get upload file as input streamServletoutputstream OS = Response.getoutputstream ();//gets the output stream pointing to the client, specifying the path output according to the client .21 22/*23 * The input stream is combined with the output stream to obtain the contents of the file before outputting the content*/25intLen =-1;26byte[] buf =New byte[1024];27 while(len = Is.read (BUF))! =-1) {28Os.write (BUF);29 }30os.close ();31is.close ();32}
File Upload and Download overview