Java File upload download
Related JAR Packages:
Commons-beanutils.jar
Commons-collections.jar
Commons-fileupload-1.2.2.jar
Commons-io-2.4.jar
Commons-lang.jar
Commons-logging.jar
Dom4j-1.6.1.jar
Ezmorph-1.0.6.jar
Jar Package Download: Http://files.cnblogs.com/files/liaolongjun/common-jar.zip
void upload () throws Exception {for (Fileitem Item:FileUtil.getFileItems (Request)) {ServletContext sc = request.gets Ervletcontext (); String Path = Sc.getrealpath ("Upload"); Uploaded file storage path string filename = Item.getname (); File File = new file (path + file.separator + filename); System.out.println (file), if (file.exists () | | file.createnewfile ()) {item.write (file);//Save file}//output Base64-item.get () Get Byte[]system.out.println ("Data:" + item.getcontenttype () + "; base64," + New String (Base64.encodebase64 (Item.get ())) );}} void Download () throws Exception {String filepath = request.getparameter ("filepath"); File File = new file (filepath); Response.reset (); Response.setcontenttype ("Application/x-msdownload"); Response.AddHeader ("Content-disposition", "attachment; Filename=\ "" + Urlencoder.encode (File.getname (), "utf-8") + "\" "); int filelength = (int) file.length (); Response.setcontentlength (filelength); FILEUTIL.I2O (New Bufferedinputstream (new FileInputStream (file)), Response.getoutputstream ());
Fileutil.getfileitems Method:
/** * Diskfileitemfactory provides the parser with the default configuration for parsing <br> * Servletfileupload parsing inputstream, a table fields (for example, a file input box) The data in a Fileitem object is encapsulated on a <br> * Fileitem object provides a method to get the data in the form field */public static list<fileitem> Getfileitems ( HttpServletRequest request) {list<fileitem> Fileitems = new arraylist<> (); try {servletfileupload SFU = new Se Rvletfileupload (New Diskfileitemfactory ()); for (Object obj:sfu.parseRequest (Request)) {Fileitem item = (fileitem) obj; if (!item.isformfield ()) {//whether plain form field fileitems.add (item);}}} catch (Exception e) {throw new RuntimeException (e);} return fileitems;}
Fileutil.i2o Method:
public static void I2o (InputStream is, OutputStream os) {try {byte[] b = new byte[1024 * 1024];//Once read 1Mint n = 0;while ( (n = is.read (b))! =-1) os.write (b, 0, n);//This n is not yet going to is.close (); Os.flush (); Os.close ();} catch (IOException e) {e.printstacktrace ();}}
Java File upload download