Using the SPRINGMVC architecture, only the key code is posted, the other is an introduction.
Upload:
JSP page
<form action= "${pagecontext.request.contextpath}/uploadhandleservlet" method= "post" enctype= "multipart/ Form-data "> Upload user x:<input type=" text "name=" username "><br/> upload file 1:<input type=" file "name=" file 1 "><br/> <input type=" Submit "value=" Submission "> </form>
Background code
Simpledateformat sdf1 = new simpledateformat ("Yyyymmddhhmmss"); String savepath =request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/upload"); File file = new file (Savepath); if (!file.exists ()) { file.mkdir (); } string message = ""; try{ diskfileitemfactory factory = new diskfileitemfactory (); factory.setsizethreshold (1024*100); Factory.setrepository (file); servletfileupload upload = new Servletfileupload (Factory); upload.setheaderencoding ("UTF-8"); list<fileitem> list = upload.parserequest (Request), //regular match, filter path take file name string regexp = ". +\\\\ (. +) $"; pattern p = pattern.compile (REGEXP); string filename= ""; for (fileitem item : list) { if (iTem.isformfield ()) { string name = item.getfieldname (); string value = item.getstring ("UTF-8"); system.out.println (name + "=" + value); }else{ string Name = item.getname (); name = name.substring (Name.lastindexof ("\ \") +1); filename = savepath+ "/" + sdf1.format (New date ()) + "_" +name; item.write (New file (fileName)); } } message = "File Upload succeeded! "; }catch (exception e) { message= " File upload failed! "; e.printstacktrace ();}
File download
Get file name and file path string name = Map.get ("name") + ""; String Path = map.get ("path") + ""; String Filename= new String (Name.getbytes ("Utf-8"), "iso8859-1"); File File = new file (path); InputStream fis = new Bufferedinputstream (new FileInputStream (path)); byte[] buffer = new Byte[f Is.available ()];fis.read (buffer); Fis.close (); Response.reset (); Response.AddHeader ("Content-disposition", " Attachment;filename= "+ New String (Name.replaceall (" "," "). GetBytes (" Utf-8 ")," iso8859-1 "); Response.AddHeader (" Content-length "," "+ file.length ()), OutputStream OS = new Bufferedoutputstream (Response.getoutputstream ()); Response.setcontenttype ("Application/octet-stream"); os.write (buffer);//Output file Os.flush (); Os.close ();
This article is from the "Bulajunjun" blog, make sure to keep this source http://5148737.blog.51cto.com/5138737/1774535
Java File upload download