Java File upload download

Source: Internet
Author: User
Tags string format to domain

File upload first to introduce two core packages

Commons-fileupload-1.2.1.jar

Commons-io-1.4.jar

Here is a simple package for uploading and downloading some of the code, so that you can use it directly in the future using the packaged jar package directly into the project.

Upload file Core code

  1 package com.lizhou.fileload;  2 3 Import Java.io.File;  4 Import Java.io.FileOutputStream;  5 Import java.io.IOException;  6 Import Java.io.InputStream;  7 Import Java.io.OutputStream;  8 Import java.util.ArrayList; 9 Import java.util.List; Ten import Java.util.UUID; Import Javax.servlet.http.HttpServletRequest; Import Org.apache.commons.fileupload.FileItem; Org.apache.commons.fileupload.FileUploadException import; Org.apache.commons.fileupload.disk.DiskFileItemFactory import; + Import Org.apache.commons.fileupload.servlet.ServletFileUpload; Import com.lizhou.exception.FileFormatException; Import com.lizhou.exception.NullFileException; Com.lizhou.exception.ProtocolException import; Import com.lizhou.exception.SizeException; 23 24/** 25 * Upload file * * @author Bojiangzhou * * * * * * * * * * * * * FileUpload {30/** 31 * Temporary directory for uploading files */-Private String TempPath = null; 34/** 35 * file directory for uploading files */Notoginseng Private String filePath = null; 38/** 39 * The size of the in-memory buffer, the default 100k * * * the private int buffersize = 100; 42/** 43 * The maximum size of the uploaded file, default 1M */private int fileSize = 1000; 46/** 47 * Upload the file using the encoding method, the default UTF-8 * */the private String encoding = "UTF-8"; 50/** 51 * Format of uploaded files, default no format limit * */list<string> FileFormat = new arraylist<string> (); /** * HttpServletRequest * * * * HttpServletRequest request; 58//privatization of non-parametric construction of the private FileUpload () {} The public FileUpload (HttpServletRequest request) {th Is.request = Request; FileUpload (String TempPath, String filePath, HttpServletRequest request) {THIS.R Equest = Request; This.temppath = TempPath; This.filepath = FilePath; Makedirectory (TempPath); Makedirectory (FilePath); 71} 72 73/** 74 * Upload file * * @reTurn upload Successful return true * * @throws protocolexception * @throws fileuploadexception * @throws nullfileexcept     Ion * @throws sizeexception * @throws fileformatexception Bayi * @throws IOException 82 */83 public Boolean UploadFile () throws Protocolexception, Nullfileexception, Sizeexception, Fileformatexceptio         N, IOException, fileuploadexception{, Boolean B = true; Servletfileupload upload = Getupload (); 87 Parses the fields in the request, and each field (upload field and normal field) is automatically wrapped in fileitem list<fileitem> fileitems = Upload.parserequest (This . request);                 Fileitem Item:fileitems {90//If the normal field is if (Item.isformfield ()) {92 Continue 93} 94//Get file name in the String filename = Item.getname (); 96//Because IE6 gets the full path of the file, it further deals with the filename.substring fileName = the filename.lastindexof ("\ \") +1);      98//Determine if the uploaded file is empty 99       if (item.getsize () <= 0) {b = false;101 throw new Nullfileexception (); 102 }103//Determine if the file exceeds the size of the limit 104 if (item.getsize () > filesize*1000) {fals e;106 throw new Sizeexception (); 107}108//Determine if the format of the uploaded file is correct 109 if (!isfor Mat (Filename.substring (Filename.lastindexof (".")             +1)) {b = false;111 throw new Fileformatexception (); 112}113 String uuidfilename = Getuuidfilename (fileName); 114//Gets the input stream of the file InputStream is = item.getinputst             Ream (); 116//Create output stream 117 outputstream os = new FileOutputStream (this.filepath+ "/" +uuidfilename); 118 Outputs 119 output (is, OS); 120//delete the temporary files generated when uploading the files 121 item.delete (); 122} 123 return b;124}125 126/**127 * Get file Upload input stream * @return129 * @throws ProtocolException130 * @throws NullFileException131 * @throws SizeException132 * @throws Fileforma tException133 * @throws IOException134 * @throws FileUploadException135 */136 public InputStream GETUPL Oadinputstream () 137 throws Protocolexception, Nullfileexception, Sizeexception, Fileformatexception, IOExcept Ion, fileuploadexception{138 servletfileupload upload = Getupload (); 139//parse the fields in request, each field (upload field and normal field) will be Dynamic packaging to Fileitem list<fileitem> fileitems = upload.parserequest (this.request); 141 for (Fileitem item             : fileitems) {142//If the normal field 143 if (Item.isformfield ()) {144 continue;145             }146//Get file name 147 String filename = item.getname (); 148//Because IE6 gets the full path of the file, further processing 149 FileName = filename.substring (filename.lastindexof ("\ \") +1); 150//Determine if the uploaded file is empty 151 if (ITEM.G   Etsize () <= 0) {152              throw new Nullfileexception (); 153}154//Determine if the file exceeds the size of the limit 155 if (item.getsiz             E () > filesize*1000) {156 throw new sizeexception (); 157}158//Determine the format of the uploaded file is correct 159 if (!isformat (filename.substring) (Filename.lastindexof (".") +1)) {fileformatexception new (); 161}162//Get the file input stream 163 Inpu     TStream is = Item.getinputstream (); 164 165 return is;166}167 return null;168      }169 170/**171 * Get the core of the uploaded file 172 * @return ServletFileUpload173 * @throws protocolexception 174 */175 public Servletfileupload Getupload () throws protocolexception{176//Create upload file factory 177 diskfileitemfact         Ory factory = new Diskfileitemfactory (); 178//Set the size of the in-memory buffer 179 factory.setsizethreshold (buffersize); 180             If the user does not set the upload file directory, set the default directory 181 if (FilePath = = null) {182Setdefaultfilepath (); 183}184//If the user does not set a temporary storage directory, set the default directory 185 if (TempPath = = null) {186 setd         Efaulttemppath (); 187}188//Set temporary storage directory for uploaded files 189 factory.setrepository (new file (This.temppath)); 190         Create an upload file object [core]191 servletfileupload upload = new Servletfileupload (factory); 192//Set the encoding method of the uploaded file 193 Upload.setheaderencoding (this.encoding); 194/*195 * Determine if the client uploads the file using the MIME protocol 196 * Only if the text is uploaded as a MIME protocol Upload to parse the field in Request 197 */198 if (!upload.ismultipartcontent (this.request)) {199 throw new Protocolexception ();}201 return upload;202}203 204/**205 * Output 206 * @param IS20 7 * @param os208 * @throws IOException209 */210 public void output (InputStream is, OutputStream OS) thr  oWS ioexception{211 byte[] by = new byte[1024];212 int len = 0;213 while (len = Is.read (by)) > 0) {214 OS.Write (by, 0, Len); 215}216 Is.close (); 217 os.close (); 218}219 220/**221 * Determine upload file 222 * @param format file Format 223 * @return boolean224 */225 Private boolean Isformat (String format) {2             if (fileformat.size () = = 0) {227 return true;228}229 for (String F:fileformat) {230 if (f.equalsignorecase (format)) {231 return true;232}233}234 retur       n false;235}236 237/**238 * Returns the UUID name of the file to prevent duplicate file names 239 * @param filename File name * @return UUID name 241 */242 public string Getuuidfilename (string fileName) {243 return Uuid.randomuuid (). toString () + "#" +filenam  e;244}245 246/**247 * Set Default temp directory 248 */249 private void Setdefaulttemppath () {TempPath      = filepath+ "/temp"; 251 252 makedirectory (TempPath); 253}254 255/**256 * Set Default file directory 257 * Default on D-plate 258 */259    private void Setdefaultfilepath () {260 FilePath = "D:/uploadfile"; 261 262 makedirectory (Filepat h); 263}264 265/**266 * Create a directory based on the given file directory 267 * @param filePath268 */269 private void Makedirec Tory (String FilePath) {File File = new file (filePath); 271 if (!file.exists ()) {272 File.mkdir (); 273}274}275 276 277 278/**279 * Get temp directory 280 * @return281 */282 public S Tring GetTempPath () {283 return temppath;284}285/**286 * Set TEMP directory 287 * @param tempPath288 * /289 public void Settemppath (String temppath) {290 This.temppath = temppath;291 makedirectory (temppath ); 292}293/**294 * Get file path 295 * @return296 */297 public String GetFilePath () {298 retur n filepath;299}300/**301 * Return file path 302 * @param filePath303 */304 public void SetFilePath (Strin        G FilePath) {305 This.filepath = filepath;306 makedirectory (filePath); 307}308/**309 * Get in-memory buffer size 310 * @return3      */312 public int getbuffersize () {313 return buffersize;314}315/**316 * Set in-memory buffer size 317 * Default 100k318 * @param bufferSize319 */320 public void setbuffersize (int buffersize) {321 This.bu Ffersize = buffersize;322}323/**324 * Gets the maximum size of the uploaded file 325 * @return326 */327 public int Getfilesiz E () {328 return filesize;329}330/**331 * Limit the maximum size of uploaded files in k332 * Default 1000k333 * @param filesi      ze334 */335 public void setfilesize (int fileSize) {336 this.filesize = filesize;337}338/**339 * Returns the encoding of the uploaded file 340 * @return341 */342 public String getencoding () {343 return encoding;344}34 5/**346 * Set the encoding of the uploaded file 347 * default UTF-8 format 348 * @param encoding349 */350 public void setencoding (St     Ring encoding) {351    this.encoding = encoding;352}353/**354 * Get the format to allow uploading of files 355 * @return356 */357 public String Getfileformat () {358 if (fileformat.size () = = 0) {359 return "*";}361 String format = ""; 362 for (String s:fileformat) {363 format + = "," +s;364}365 format = Format.substri Ng (Format.indexof (",") +1); 366 return format;367}368/**369 * Sets the format of the uploaded file, multiple file formats are called the method multiple times to set 370 *     @param fileFormat371 */372 public void Setfileformat (String format) {373 this.fileFormat.add (format); 374 }375 376 Public HttpServletRequest getrequest () {377 return request;378}379 380 public vo ID setrequest (HttpServletRequest request) {381 this.request = request;382}383 384}

Download the file Core code

  1 package com.lizhou.fileload;  2 3 Import Java.io.File;  4 Import Java.io.FileInputStream;  5 Import java.io.FileNotFoundException;  6 Import java.io.IOException;  7 Import Java.io.InputStream;  8 Import Java.io.OutputStream; 9 Import java.io.UnsupportedEncodingException; Ten import Java.net.URLEncoder; Import java.util.ArrayList; Import java.util.List; Import Javax.servlet.http.HttpServletRequest; Javax.servlet.http.HttpServletResponse import; Com.lizhou.domain.DownloadFile import; Import com.lizhou.exception.FileNotExistsException; 19 20/** 21 * Download file * @author Bojiangzhou * * * * * * * * * * * * * * * * * * * * * * * * * FileDownload {26/** 27 * Download default file Record: * * private String FilePath = null; 30/** 31 * Format of the file to be downloaded * */list<string> FileFormat = new arraylist<string> (); /** * httpservletrequest * */PNS HttpServletRequest request; The Public filedownload (HttpserVletrequest request) {this.request = Request; n-filedownload (String FilePath, Http ServletRequest request) {this.request = Request; this.filepath = FilePath; 46} 47 48/      * * 49 * Bind download list to domain 50 * Default session * * @param var Field object variable name filenotexistsexception * @throws 53  * * * public void Binddownloadfilestoscope (String var) throws filenotexistsexception{if (FilePath = = null) { FilePath = "D:/uploadfile"; (!isfileexists (This.filepath)) {60} (); list<downloadfile> List = new arraylist<downloadfile> (); Getdownloadfiles (FilePath, list); Request.getsession (). SetAttribute (Var, list); 64} 65 66/** 67 * Get all the files in the download directory. * @param filePath * @param list * * Priv ate void Getdownloadfiles (String filePath, List<downloadfile> list) {File File = new file (FilePath); if (File.isfile ()) {n-S Tring Uuidfilename = File.getname (); Isformat (Uuidfilename.substring (Uuidfilename.lastindexof (".") +1)) {DownloadFile df = new DownloadFile (); Df.setfilename (uuidfilename.substring (U Uidfilename.indexof ("#") +1)); Df.setuuidfilename (Uuidfilename); Df.setfilepath (File.getpath ()); List.add (DF); Bayi} else{file[] childfiles = File.listfiles (), + (File Cf:chil Dfiles) {getdownloadfiles (Cf.getpath (), list); 86} 87} 88} 89 90/*      * 91 * Download File * * @param var download list domain variable name uuidfilename * @param the name of the file that came from the client 94 * @param response 95 * @throws IOException * */DownloadFile public void (string var, string uuidfilename, HttpServletresponse response) throws ioexception{98 byte[] by = uuidfilename.getbytes ("iso-8859-1"); UUIDF Ilename = new String (by, "UTF-8"); list<downloadfile> files = (list<downloadfile>) this.request.get Session (). getattribute (Var); 101 for (DownloadFile file:files) {102 if (File.getuuidfilename (). Equals (UU  Idfilename) {103 InputStream is = new FileInputStream (File.getfilepath ()); 104 OutputStream OS = Response.getoutputstream (); Response.setheader ("Content-disposition", "attachment"; Filename= "+urlencoder.encode (File.getfilename ()," UTF-8 "); 106 output (IS, OS); 107 break;10 8}109}110}111 public void output (InputStream is, OutputStream os) throws Ioexceptio             n{113 byte[] by = new byte[1024];114 int len = 0;115 and (len = Is.read (by)) > 0) {116       Os.write (by, 0, Len); 117  }118 is.close (); 119 os.close (); 120}121 122/**123 * Determine if the file is properly formatted 124 * @param forma T file format boolean126 * @return */127 Private boolean Isformat (String format) {(Fileformat.size ( ) = = 0) {129 return true;130}131 for (String F:fileformat) {if (F.equalsignorec     ASE (format)) {133 return true;134}135}136 return false;137}138 139 /**140 * Determine if the file directory exists 141 * @param filePath file directory 142 * @return boolean143 */144 Private Boolean IsF Ileexists (String FilePath) {145 Boolean b = true;146 file File = new file (FilePath); 147 if (!file.ex         Ists ()) {148 b = false;149}150 return b;151}152 153 public String GetFilePath () {154 return filepath;155}156 157/**158 * Set Download Path 159 * @param filePath160 * @throws filenote xistsException161 */162 public void SetFilePath (String filePath) {163 This.filepath = filepath;164}165 166/**167 * Get the format to allow uploading files 168 * @return169 */170 public String Getfileformat () {171 if (fileformat.size () = = 0)             {172 return "*"; 173}174 string format = ""; 175 for (String S:fileformat) {176      Format + = "," +s;177}178 format = format.substring (Format.indexof (",") +1); 179 return format;180 }181/**182 * Set the format of the uploaded file, multiple file formats call the method multiple times to set 183 * @param fileFormat184 */185 public void Setfile  Format (String format) {186 this.fileFormat.add (format); 187}188 189 public HttpServletRequest getrequest () {request;191}192 193 public void Setrequest (HttpServletRequest request) {194 This.req uest = request;195}196 197}

Note: When uploading a file, the foreground form form must have the following properties: Enctype= "Multipart/form-data"

Attach source + exported jar Package + Use Demo: Download file

Java File upload download

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.