Java implementation File Upload (verify file size, file type)

Source: Internet
Author: User

File uploads are what every Java developer must master. There are many ways to implement file uploads, but in fact they are quite similar. The pen person here introduces a kind of way that I used to upload files. Everyone first look at the code, and finally I will share my source to everyone.

    • 1, first to prepare a need to use the jar package.
      • Commons-fileupload-1.2.1.jar
        -commons-io-1.4.jar
        can be downloaded from [(http://commons.apache.org/)], of course, my project source code also has
        Then start writing the code.
 PublicStaticStringFileUpload (httpservletrequest request,httpservletresponse response) throws exception{//Allow upload of file types    StringFileType= "Mp3,mp4,video,rmvb,pdf,txt,xml,doc,gif,png,bmp,jpeg";maximum size of files allowed to upload (100M, in bytes)int MaxSize= 1024x768*1024x768* -; Response.AddHeader ("Access-control-allow-origin","*");//path to save the file    StringSavepath=Request.Getrealpath ("/")+ "save/"; Response.setContentType ("text/html; Charset=utf-8 ");//Check directoryFile Uploaddir= NewFile (Savepath);if(!Uploaddir.Exists ()) {Uploaddir.Mkdirs (); }if(!Uploaddir.CanWrite ()) {returnGetError ("Upload directory does not have write permission!" "); } Diskfileitemfactory Factory= NewDiskfileitemfactory (); Factory.Setsizethreshold (1024x768 * 1024x768);//Set buffer size, this is 1MFactory.Setrepository (Uploaddir);//Set buffer directoryServletfileupload Upload= NewServletfileupload (Factory); Upload.Setheaderencoding ("UTF-8");ListItems=Upload.Parserequest (Request); Iterator it=Items.Iterator (); Fileitem Item= NULL;StringFileName= "";StringName= "";StringExtname= "";StringNewFileName= ""; while(It.Hasnext ()) {Item=(Fileitem) it.Next (); FileName=Item.GetName ();if(NULL ==FileName|| "".equals(FileName))        {continue; }//Determine if the file size is overrun        if(item.GetSize ()>MaxSize) {Item.Delete (); Joptionpane.Showmessagedialog (NULL,"File size exceeds limit!" Should be less than " +MaxSize/ 1024x768 / 1024x768 + "M");return; }//Determine if the file type matches        //System.getproperties (). GetProperty ("File.separator"))        //Get file nameName=FileName.SUBSTRING (fileName.LastIndexOf ("\\")+ 1, FileName.LastIndexOf ("."));//Get file suffix nameExtname=FileName.SUBSTRING (fileName.IndexOf (".")+ 1).toLowerCase ().Trim ();//Determine if the file type is allowed to be uploaded        if(!Arrays.<String>Aslist (FileType.Split",")).Contains (Extname)) {Item.Delete (); Joptionpane.Showmessagedialog (NULL,"The file type is incorrect and must be" +FileType+ "The file! ");return; } SimpleDateFormat DF= NewSimpleDateFormat ("YYYYMMDDHHMMSS"); NewFileName=Name+Df.FormatNew Date())+ "." +Extname; } File UploadedFile= NewFile (Savepath, NewFileName); Item.Write (UploadedFile);return "Success";}

The above code is OK. Some of my parameters are written to death, such as the size of the allowed file upload, and the type of file. It is best to write in a configuration file, and then go to read this configuration file, get the parameters inside. Although the parameters in the configuration file is also written dead, but the meaning is different, as a programmer you are to provide others with convenience, it is impossible to change the code every time, only need to change the configuration file on it. This also requires us to be intelligent.

Of course, the above code just do upload function, below I will share my source code, the source is written in the configuration file, and then, if the upload file does not meet the requirements, will return the information to the foreground visual display.

Below to share my source: File Upload

If you encounter problems, we can exchange and learn from each other!

Java Implementation File upload (verify file size, file type)

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.