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 =
NewBufferedinputstream (in );
Bufferedout =
NewBufferedoutputstream (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.