The first method is implemented using the responseentity<> under Httpmessageconverter.
@RequestMapping ("/testhttpmessagedown") Publicresponseentity<byte[]> Download (httpservletrequest request)throwsioexception{String filename= "123.jpg"; //file name garbled problem when downloading according to different browsers if(Request.getheader ("User-agent"). toUpperCase (). IndexOf ("MSIE") > 0) {filename= Urlencoder.encode (filename, "UTF-8"); } Else{filename=NewString (Filename.getbytes ("UTF-8"), "Iso8859-1"); } byte[] BODY =NULL; InputStream is= Request.getsession (). Getservletcontext (). getResourceAsStream ("/upload/user/json.jpg"); Body=New byte[Is.available ()]; Is.read (body); Httpheaders Headers=Newhttpheaders (); Headers.add ("Content-disposition", "attchement;filename=" +filename); Httpstatus StatusCode=Httpstatus.ok; Responseentity<byte[]> entity =Newresponseentity<byte[]>(body, headers, statusCode); returnentity; }
The second method is the commonly used file download method
@RequestMapping ("/testfiledown") Public voidFileDownload (HttpServletRequest request, httpservletresponse response)throwsioexception{String filename= "This is the Chinese name 123abc () ()-2,340 minutes. pdf"; //file name garbled problem when downloading according to different browsers if(Request.getheader ("User-agent"). toUpperCase (). IndexOf ("MSIE") > 0) {filename= Urlencoder.encode (filename, "UTF-8"); } Else{filename=NewString (Filename.getbytes ("UTF-8"), "Iso8859-1"); }//Response.setcontenttype ("Multipart/form-data");Response.setcharacterencoding ("Utf-8"); Response.setheader ("Content-disposition", "attachment;filename=" +filename); InputStream is= Request.getsession (). Getservletcontext (). getResourceAsStream ("Name of the/upload/user/Chinese name. pdf"); OutputStream OS=Response.getoutputstream (); byte[] B =New byte[1024]; intLength = 0; while(length = Is.read (b)) > 0) {os.write (b); } os.flush (); Os.close (); Is.close (); }
SPRINGMVC File Download