File Upload: smartupload and fileupload

Source: Internet
Author: User
Tags custom name
Document directory
  • 1. General Code Flow
  • 2. form considerations
  • 3. Obtain the values of other common controls in the form.
  • 4. Custom storage file name
  • 5. Random file name
  • 6. Batch upload
  • 1. General Code Flow
  • 2. differentiate general control data and file upload Control Data
  • 3. fileitem usage
  • 4. Save the file
  • 5. Get the file suffix
  • 6. For large files
I. Introduction to File Upload

In HTML

<Form action = "" method = "Post" enctype = "multipart/form-Data">

<Input type = "file" name = "upload1"/> <br/>

<Input type = "Submit" value = "Upload"/>

</Form>

Format.

There are two options for file upload:

(1) smartupload: it appears as a jar package. You need to add it to the classpath or Tomcat lib folder.

(2) fileupload: it appears as a jar package. You need to add it to the classpath or Tomcat lib folder. Note: this package is mutually dependent on the common-io package, so it must be stored at the same time.

Smartupload is easy to use, but cannot be downloaded officially.

Ii. smartupload1. General Code Process

Smartupload smart = new smartupload ();

Smart. initialize (pagecontext );

Smart. Upload (); // prepare for upload

Smart. Save ("file ");

The function is to save the uploaded files in the/file folder and save them with the same name.

2. form considerations

File Upload rules: the form must have the enctype = "multipart/form-Data" attribute. Therefore, the form is sent in binary data. For example, the form has one text and two upload controls, data is sent in binary format.

3. Obtain the values of other common controls in the form.

With the File Upload control, other controls of the form cannot pass data through common request. getparameter (), but smart. getrequest (). getparameter ();

4. Custom storage file name

String ext =Smart. getfiles (). GetFile (0). getfileext ();// Obtain the file suffix

Smart. getfiles (). getFile (0 ). saveas (this. getservletcontext (). getrealpath ("/") + filename + ". "+ ext); // save it as a custom file name

Filename is the custom name of the file, and ext is the file extension.

5. Random file name

Package Org. random; import Java. util. *; import Java. text. *; public class iptimestamp {private stringbuffer Buf; private string IP; Public iptimestamp (string IP) {// input the request parameter. getremoteaddr (); then this. IP = IP; Buf = new stringbuffer ();} Public String getrandomfilename () {// get the file name simpledateformat SDF = new simpledateformat ("yyyymmddhhmmsssss "); string [] ipadd = IP. split ("\\. "); For (string IPA: ipadd) {Buf. append (IPA);} Buf. append (SDF. format (new date (); random ran = new random (); For (INT I = 0; I <3; I ++) {Buf. append (ran. nextint (10);} return Buf. tostring ();}}

6. Batch upload

For (INT I = 0; I <smart. getfiles ().Getcount(); I ++ ){

String ext = smart. getfiles (). GetFile (I). getfileext ();

Smart. getfiles (). GetFile (I). saveas (this. getservletcontext (). getrealpath ("/") + filename + "." + ext );

.

From the above, we can see that the amount of smartupload code is not very large and convenient.

Iii. fileupload Template code:
Boolean ismultipart = servletfileupload. ismultipartcontent (request); If (ismultipart) {// type = multipart/form-datadiskfileitemfactory factory = new diskfileitemfactory (); servletfileupload upload = new servletfileupload (factory); upload. setfilesizemax (1024*1024); // sets the maximum capacity of the uploaded file list <fileitem> items = upload. parserequest (request); // get all data in the form for (fileitem item: Items) {If (item. isformfield () {// if it is not of the file type // string name = item. getfieldname (); name of a widget in the form // string value = item. getstring (); Value of a control in the form} else {// string filename = item. getname (); returns the file name file F = NULL; // saved file item. write (f); // save the file }}} else {// if no file is uploaded}

Fileupload is a sub-project of the Apache Commons project, you need to download the jar package, note: also put the commons-io.jar down, because the two packages are correlated.

Import:

(1) org. Apache. commons. fileupload .*;

(2) org. Apache. commons. fileupload. servlet .*;

(3) org. Apache. commons. fileupload. disk .*;


1. General Code flow Boolean ismultipart = servletfileupload. ismultipartcontent (request); // judge whether the form type is multipart/form-Data

Diskfileitemfactory factory = new diskfileitemfactory ();

Servletfileupload upload = new servletfileupload (factory );

Upload. setfilesizemax (1024*1024); // sets the maximum size of the uploaded file.

List <fileitem> items = upload. parserequest (request); // Retrieves all data from the form.

Forms containing File Upload controls cannot distinguish between general controls and upload controls. They are used as fileitem;

2. differentiate general control data and file upload Control Data

You can use item. isformfield () to determine whether to return true, which indicates the data of the general control.

3. fileitem usage

(1) for general controls, item. getstring.

Item. getfieldname () returns the domain name.

(2) if it is a file upload control, it contains some methods

Item. getname (); get the name of the uploaded file

Item. getcontenttype (); obtain the MIME type of the uploaded file

Long item. getsize (); get the size of the uploaded file

Item. getinputstream (); get the input stream of the uploaded file

4. Save the file

In smartupload, you only need to save the function, but in fileupload, Io stream is required.

Inputstream input = item. getinputstream ();

Fileoutputstream output = new fileoutputstream ("file.txt ");

Byte [] Buf = new byte [1, 1024];

Int length = 0;

While (length = input. Read (BUF ))! =-1 ){

Output. Write (BUF, 0, length );

}

Input. Close ();

Output. Close ();

You can.

5. Get the file suffix

String ext = item. getname (). Split ("\.") [1];

6. For large files

For file preparation, you need to set a temporary folder in the form:

Factory. setrepository ("FILENAME ");

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.