1Request.setcharacterencoding ("Utf-8");2String name=request.getparameter ("name");3 //1. Set the response header4Response.setcontenttype ("Application/force-download");5 //2. Read the file6String Path=getservletcontext (). Getrealpath ("/file/" +name);7InputStream in=NewFileInputStream (path);8 //3. Encode the file name9Name=urlencoder.encode (name, "Utf-8"));Ten //4. Set the response header OneResponse.setheader ("Content-disposition", "attachment;filename=" +name);//If you do not write attachment, it will open in the browser A response.setcontentlength (In.available ()); - //5. Start Copy file -OutputStream out=Response.getoutputstream (); the byte[] b=New byte[1024]; - intLen=-1; - while((Len=in.read (b))!=-1) - { +Out.write (b, 0, Len); - } + out.close (); A in.close (); at - -}
Written in servlet to prevent hotlinking, filtering and other operations
Java Download servlet Demo