Implement the page upload image Function

Source: Internet
Author: User

Page code:

<Input type = "file" name = "picture"/> upload an image <br/>

The key is to add an attribute when submitting a form.

<Forpolichod = "Post" id = "form" Action = "register! Inland_p.action "enctype =" multipart/form-Data ">

When obtaining antion:

Define three variables

PrivateFile
Picture;

PrivateString
Picturecontenttype;

PrivateString
Picturefilename;

Add the Set Method

Struts2 automatically uploads the image file to the action

Save to the specified path:

// Save the image

PrivatevoidSavaimage (File picture, string path, stringpicturefilename ){

 

Fileinputstream in =
Null
;

Fileoutputstream out =
Null
;

Bufferedinputstream bufferedin =
Null;

Bufferedoutputstream bufferedout =
Null;

Try{

//
Save image to local

In =NewFileinputstream (picture );

Out =NewFileoutputstream (path + picturefilename );

Bufferedin =
New
Bufferedinputstream (in );

Bufferedout =
New
Bufferedoutputstream (out );

Byte[] DATA =
Newbyte[1];

While(Bufferedin. Read (data )! =-1 ){

Bufferedout. Write (data );

}

//
Write all data in the buffer

Bufferedout. Flush ();

//
Close stream

In. Close ();

Out. Close ();

Bufferedin. Close ();

Bufferedout. Close ();

}Catch(Exception e ){

E. printstacktrace ();

}Finally{

Try{

//
Close stream

If(In! =
Null){

In. Close ();

}

If(Out! =
Null){

Out. Close ();

}

If(Bufferedin! =
Null){

Bufferedin. Close ();

}

If(Bufferedout! =
Null){

Bufferedout. Close ();

}

}Catch(Ioexception e ){

E. printstacktrace ();

}

}

}

 

Image verification methods: (the code can be found on the Internet)

1. Determine the file type

2. Determine the first few characters of the file

3. determine the length and width of the file to determine whether it is an image (recommended)

4. processing of malicious images is not done for the moment. Only anti-virus software on the server can be expected.

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.