Struts2 File Upload

Source: Internet
Author: User

Upload a file in two steps:

1. Page

<Form action = "addhomead.htm" method = "Post" onsubmit = "Return checkform ()" enctype ="Multipart/form-Data"Name =" form1 "id =" form1 ">
<Table width = "600" border = "1">

 

<Tr>
<TD> upload an image </TD>
<TD> <label>
<Input type = "file" name = "IMG" id = "IMG" onkeydown = "event. returnvalue = false;"/>
</Label> </TD>
</Tr>

<Tr>
<TD> & nbsp; </TD>
<TD> <label>
<Input type = "Submit" name = "bunupload" id = "bunupload" value = "Submit"/>
</Label> </TD>
</Tr>
</Table>
</Form>

 

2. Action

Public class addhomead extends actionsupport {
 
Private ihomeadserver homeadserver;
Private file IMG;
Private string imgfilename;
Private string imgcontenttype;
Private string URL;
Private string ALT;
Private integer priority;
Private string basedir;
Private string dir; // The generated dir
Private string userupload = "userupload ";
Private string ImagePath;
 

@ Override
Public String execute () throws exception {
String newfilename;
String dirtime;
Try {
// System. Out. println ("file length:" + IMG. Length ());
Basedir = servletactioncontext. getservletcontext (). getrealpath (userupload );
Dirtime = uploadfile. gettimebyformat ("yyyymm ");
Dir = basedir + "//" + dirtime;
If (! (New file (DIR). isdirectory () {// if this folder is not saved, create it
New file (DIR). mkdir ();
}
Newfilename = uploadfile. getnewfilename (imgfilename); // you can specify a file name.
String saveimagepath = dir + "//" + newfilename;
Uploadfile. Copy (IMG, saveimagepath); // save file parameter 1 file parameter 2 file in the absolute save path

} Catch (exception ex ){
Ex. printstacktrace ();
Uploadfile. outmessage ("unable to upload images ");
Return success; // if the file cannot be uploaded, the system returns
}
String ImagePath = userupload + "/" + dirtime + "/" + newfilename;

Homead = new homead ();
Homead. setalt (ALT );
Homead. seturl (URL );
Homead. setimg (ImagePath );
Homead. setimgtime (uploadfile. getnowdatetime (); // return the current system time
Homead. setpriority (priority );
Homeadserver. addhomead (homead );
Uploadfile. outmessage ("image uploaded successfully! ");
Return success;
}

 

 

Private Static final int buffer_size = 16*1024;
// A self-encapsulated object that copies the source object to the target object
Public static void copy (File oldfile, string filepath ){
Try {
File newfile = new file (filepath );
Inputstream in = NULL;
Outputstream out = NULL;
Try {
In = new bufferedinputstream (New fileinputstream (oldfile), buffer_size );
Out = new bufferedoutputstream (New fileoutputstream (newfile ),
Buffer_size );
Byte [] buffer = new byte [buffer_size];
Int Len = 0;
While (LEN = in. Read (buffer)> 0 ){
Out. Write (buffer, 0, Len );
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (null! = In ){
Try {
In. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
If (null! = Out ){
Try {
Out. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
} Catch (exception ex ){
System. Out. println ("file cannot be created" + ex. tostring ());
}

}

 

// Create a new file name
Public static string getnewfilename (string filename ){
Java. util. Date = new java. util. Date (system. currenttimemillis ());
// Format the time
Java. Text. simpledateformat SDF = new java. Text. simpledateformat ("yyyymmdd_hhmmss ");
String S = SDF. Format (date );
Random ran = new random ();
S + = "_" + ran. nextint (10000 );

Int I = filename. lastindexof (".");
System. Out. println (I );
String STR = "";
If (I <0)
STR = filename;
Else
STR = filename. substring (I, filename. Length ());
S + = STR;
Return S;
}
 
 
// Output information and direct it to the specified address. js implementation
Public static void outmessage (string message)
{
Try
{
Httpservletresponse response = servletactioncontext. getresponse ();
Response. setcontenttype ("text/html; charset = UTF-8 ");
Response. setheader ("cache-control", "No-Cache ");

Printwriter out = response. getwriter ();
Stringbuffer buffer = new stringbuffer ();
Buffer. append ("<SCRIPT type =/" text/JavaScript/"> ");
Buffer. append ("alert ('" + message + "');");
// Buffer. append ("window. navigate (/" "+ newurl + "/");");
Buffer. append ("history. Go (-1 );");
Buffer. append ("</SCRIPT> ");
String S = buffer. tostring ();
Out. println (s );
Out. Flush ();
Out. Close ();

} Catch (exception ex)
{
System. Out. println (ex. tostring ());
}
}

// Returns the Time of the string type.
Public static string gettimebyformat (string format ){
Try {
Java. util. Date = new java. util. Date (system. currenttimemillis ());
// Format the time
Java. Text. simpledateformat SDF = new java. Text. simpledateformat (format );
String S = SDF. Format (date );
Return S;
} Catch (exception ex ){
System. Out. println ("format error:" + ex. tostring ());
}
Return NULL;

}
 
// Return the current system time. It is applicable to the hibernate datetime field.
Public static timestamp getnowdatetime (){
Date = new date ();
Timestamp nousedate = new timestamp (date. gettime ());
Return nousedate;
}

}

 

 

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.