import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
*
* @author xiongjitao
*
* @version $Rev$
*/
public class ActionFileUpload extends ActionSupport{
private File upfile;
private String fileName;
private String contentType;
private ServletActionContext context;
public String execute() throws Exception
{
String targetDirectory =ServletActionContext.getServletContext().getRealPath("/");
// targetDirectory = context.get.getRealPath("/upload");
String targetFileName = generateFileName(upfile.getAbsolutePath());
File target = new File(targetDirectory, targetFileName);
copy(upfile, target);
return super.execute();
}
public File getUpfile() {
return upfile;
}
public void setUpfile(File upfile) {
this.upfile = upfile;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public ServletActionContext getContext() {
return context;
}
public void setContext(ServletActionContext context) {
this.context = context;
}
private String generateFileName(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
private void copy(File source, File dest) {
try {
FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int c=-1;
while((c = fis.read(buf))!=-1)
{
fos.write(buf,0,c);
}
fos.flush();
fos.close();
fis.close();
}
catch (Exception e) {
}
}
}