Struts2 image Upload

Source: Internet
Author: User

Struts2 itself with the upload function, so only need to import the corresponding package can be used, the specific package, you can search the Internet, do not list.

Check the foreground code first:

<form action= "Fileupload_upload" method= "post" enctype= "Multipart/form-data" >

<table>

<tr>

<td> Uploading Files:</td>

<td><input type= "File" Name= "MyFile" ></td>

</tr>

<tr>

<td><input type= "Submit" value= "Upload" ></td>

<td><input type= "Reset" ></td>

</tr>

</table>

</form>

You can see that when you click Upload, you call fileupload_upload.action, so to find out which of the classes in the fileupload_upload.action corresponds to Struts.xml.

When found, it is the following class:

Import java.io.*;


Import com.arche.alderman.mvc.base.controller.BaseAction;

Import Org.apache.struts2.ServletActionContext;


/**

* Created by Hexiaoyu on 2015/5/18.

*/


public class FileUpload extends Baseaction {

Private File MyFile;

Private String Myfilecontenttype;

Private String Myfilefilename;


/**

* File Upload

* @return

* @throws Exception

*/

Public String upload () throws Exception {

InputStream InputStream = new FileInputStream (myFile);

String Uploadpath = Servletactioncontext.getservletcontext ()

. Getrealpath ("/");

File ToFile = new file (Uploadpath,this.getmyfilefilename ());

OutputStream OS = new FileOutputStream (tofile);

byte[] buffer = new byte[1024];


int length = 0;

while (length = inputstream.read (buffer)) > 0) {

Os.write (buffer, 0, length);

}


Is.close ();

Os.close ();


Setserverresponseresult (Responsestatuscode.rep_server_handle_success, myfilefilename+ "_" +myFileContentType, null );

return Servercommonstring.action_result_json;

}


Public File Getmyfile () {

return myFile;

}

public void Setmyfile (File myFile) {

This.myfile = MyFile;

}

Public String Getmyfilecontenttype () {

return myfilecontenttype;

}

public void Setmyfilecontenttype (String myfilecontenttype) {

This.myfilecontenttype = Myfilecontenttype;

}

Public String Getmyfilefilename () {

return myfilefilename;

}

public void Setmyfilefilename (String myfilefilename) {

This.myfilefilename = Myfilefilename;

}


}

Uploading a picture at this time can be successful, but missing:

1. detect files with suffix names that are not pictures.

2. Detect a non-picture file that forcibly changed the suffix name to. jpg.

For resolution 1th, you need to add some interceptor configurations for file uploads in Struts.xml:


<package name= "FileUpload" extends= "global" >

<action name= "fileupload_*" class= "Com.arche.alderman.constant.FileUpload" method= "{1}" >

<result name= "Result_json" type= "JSON" >

<param name= "Root" >mResult</param>

</result>

<!--configuring FileUpload interceptors--

<interceptor-ref name= "FileUpload" >

<!--configuration allows uploading of file types--

<param name= "Allowedtypes" >image/bmp,image/png,image/gif,image/jpeg</param>

<!--configuration allows uploading of file size units bytes--

<param name= "MaximumSize" >5242880</param>

</interceptor-ref>

<interceptor-ref name= "Defaultstack"/>

</action>

</package>

Since FileUpload this interceptor is struts2, it can be used directly and then configured to allow uploading of file types and maximum bytes. This solves the first problem.

Then is the second, how to determine whether the file is a picture file, at this time I asked some great God in the OSC, we say can judge the way the file head, I tried, can succeed, only need to in the above FileUpload this class add two more methods:

/**

* Get the file header of the uploaded file

* @param src

* @return

*/

public static String bytestohexstring (byte[] src) {

StringBuilder StringBuilder = new StringBuilder ();

if (src = = NULL | | src.length <= 0) {

return null;

}

for (int i = 0; i < src.length; i++) {

int v = src[i] & 0xFF;

String HV = integer.tohexstring (v);

if (Hv.length () < 2) {

Stringbuilder.append (0);

}

Stringbuilder.append (HV);

}

return stringbuilder.tostring ();

}


/**

* Determine the file type according to the file header of the developed file

* @param is

* @return

*/

public static String Gettypebystream (InputStream is) {

Byte[] B = new Byte[4];

try {

Is.read (b, 0, b.length);

} catch (IOException e) {

E.printstacktrace ();

}

String type = bytestohexstring (b). toUpperCase ();

if (Type.contains ("ffd8ff") | | | type.contains ("89504E47") | | type.contains ("49492a00") | | type.contains ("424D")) {

return "Isimage";

}

return "Notimage";

}

And then, when you get the InputStream, call

Gettypebystream () method, the InputStream passed in, you can determine whether it is a picture file

Here need to pay special attention is, pass in the InputStream will remove the file header, so the last uploaded image is already damaged, I did not think of any good way, is to create a new InputStream, the new to upload, the two do not affect, the test can be passed. Attach the complete Fileupload.java for reference:


Import java.io.*;


Import com.arche.alderman.mvc.base.controller.BaseAction;

Import Org.apache.struts2.ServletActionContext;


/**

* Created by Hexiaoyu on 2015/5/18.

*/


public class FileUpload extends Baseaction {

Private File MyFile;

Private String Myfilecontenttype;

Private String Myfilefilename;


/**

* Get the file header of the uploaded file

* @param src

* @return

*/

public static String bytestohexstring (byte[] src) {

StringBuilder StringBuilder = new StringBuilder ();

if (src = = NULL | | src.length <= 0) {

return null;

}

for (int i = 0; i < src.length; i++) {

int v = src[i] & 0xFF;

String HV = integer.tohexstring (v);

if (Hv.length () < 2) {

Stringbuilder.append (0);

}

Stringbuilder.append (HV);

}

return stringbuilder.tostring ();

}


/**

* Determine the file type according to the file header of the developed file

* @param is

* @return

*/

public static String Gettypebystream (InputStream is) {

Byte[] B = new Byte[4];

try {

Is.read (b, 0, b.length);

} catch (IOException e) {

E.printstacktrace ();

}

String type = bytestohexstring (b). toUpperCase ();

if (Type.contains ("ffd8ff") | | | type.contains ("89504E47") | | type.contains ("49492a00") | | type.contains ("424D")) {

return "Isimage";

}

return "Notimage";

}


/**

* File Upload

* @return

* @throws Exception

*/

Public String upload () throws Exception {


InputStream is = new FileInputStream (myFile);

if ("Notimage". Equals (Gettypebystream (IS))) {

Setserverresponseresult ( -1, "File type error", NULL);

return Servercommonstring.action_result_json;

}

InputStream InputStream = new FileInputStream (myFile);

String Uploadpath = Servletactioncontext.getservletcontext ()

. Getrealpath ("/");

File ToFile = new file (Uploadpath,this.getmyfilefilename ());

OutputStream OS = new FileOutputStream (tofile);

byte[] buffer = new byte[1024];


int length = 0;

while (length = inputstream.read (buffer)) > 0) {

Os.write (buffer, 0, length);

}


Is.close ();

Os.close ();


Setserverresponseresult (Responsestatuscode.rep_server_handle_success, myfilefilename+ "_" +myFileContentType, null );

return Servercommonstring.action_result_json;

}


Public File Getmyfile () {

return myFile;

}

public void Setmyfile (File myFile) {

This.myfile = MyFile;

}

Public String Getmyfilecontenttype () {

return myfilecontenttype;

}

public void Setmyfilecontenttype (String myfilecontenttype) {

This.myfilecontenttype = Myfilecontenttype;

}

Public String Getmyfilefilename () {

return myfilefilename;

}

public void Setmyfilefilename (String myfilefilename) {

This.myfilefilename = Myfilefilename;

}


}


Struts2 image Upload

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.