package action;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class FileuploadAction extends ActionSupport {
@SuppressWarnings("unused")
private static final long serialversionUID=572146812454l;
private static final int Buffered_SIZE=100*1024;
private File myFile; //文件
private String contentType; //内容类型
private String fileName; //文件名称
private String imageFileName; //图片文件名称
private String caption; //标题
public void setMyFileContentType(String contentType) {
this .contentType = contentType;
}
public void setMyFileFileName(String fileName) {
this .fileName = fileName;
}
public void setMyFile(File myFile) {
this .myFile = myFile;
}
public String getImageFileName() {
return imageFileName;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this .caption = caption;
}
private static void copy(File src, File dst) {
try {
InputStream in = null ;
OutputStream out = null ;
try {
in = new BufferedInputStream( new FileInputStream(src), Buffered_SIZE);
out = new BufferedOutputStream( new FileOutputStream(dst), Buffered_SIZE);
byte [] br = new byte [Buffered_SIZE];
while (in.read(br) > 0 ) {
out.write(br);
}
} finally {
if ( null != in) {
in.close();
}
if ( null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getExtention(String fileName) {
int pos = fileName.lastIndexOf( "." );
return fileName.substring(pos);
}
@Override
public String execute() {
imageFileName = new Date().getTime() + getExtention(fileName);
File imageFile = new File(ServletActionContext.getServletContext().getRealPath( "/Images" ) + "/" + imageFileName);
copy(myFile, imageFile);
return SUCCESS;
}
}
<body>
This is my JSP page. <br>
<s:fielderror/> <!-- //输出错误信息标签 -->
<s:form method="post" action="fileUpload" enctype ="multipart/form-data"> <!-- // enctype="multipart/form-data"上传文件必须这样写 -->
<s:file name="myFile" label="文件位置"/>
<s:textfield name="capion" label="文件名称"/>
<br>
<s:submit value="提交"/>
</s:form>
</body>
<body>
<s:iterator>
<p><a href="http://www.hao123.com/" target="_parent">图片:</a></p>
<div style="padding:3px; border:solid 1px #cccccc; text-align:center;width:200; height:200">
<a href="http://www.hao123.com/" target="_self">
<img src="Images/<s:property value="imageFileName"/>"/>
</a>
<br/>
<s:property value="caption"/>
</div>
<p><a href="http://www.hao123.com/" target="_top">文件名称:</a></p>
<a href="http://www.hao123.com/" target="_blank"><s:property value="imageFileName"/></a>
</s:iterator>
</body>