借助struts2文件上传组件可以方便的进行文件上传与下载,这里需要commons-fileupload-1.2.2.jar,commons-io-2.1.jar两个jar包。
②后台action实现:
上传完了后,跳转到结果页面:
①前台上传界面如下:
<s:form action="uploadFile" method="post" enctype="multipart/form-data" >
请选择文件:
<s:file name ="file" id="myFile"></s:file>
<s:submit value="上传"></s:submit>
</s:form>
②后台action实现:
package edu.njcit.action.updown;
import java.io.File;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import edu.njcit.action.ActionSupportBase;
import edu.njcit.entity.UpLoadFile;
import edu.njcit.util.UpDownLoadUtil;
public class UpDownAction extends ActionSupportBase{
private static final long serialVersionUID = 1L;
private File file=null;
private UpLoadFile upLoadFile=null;
private String fileFileName;//变量名有规定
private String fileContentType;//ContentType
@Override
public String execute() throws Exception {
File saveFile=null;
try {
saveFile=UpDownLoadUtil.saveFile(request, file, fileFileName);
String absPathName=saveFile.getAbsolutePath();
upLoadFile=new UpLoadFile();
upLoadFile.setDate(new Date());
upLoadFile.setImgSrc(UpDownLoadUtil.convertAbsPathToImgSrc(absPathName));
upLoadFile.setOriginalName(fileFileName);
upLoadFile.setServerDiskPathName(absPathName);
upLoadFile.setSize(saveFile.getTotalSpace());
} catch (Exception e) {
e.printStackTrace();
}
return ActionSupport.SUCCESS;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public UpLoadFile getUpLoadFile() {
return upLoadFile;
}
public void setUpLoadFile(UpLoadFile upLoadFile) {
this.upLoadFile = upLoadFile;
}
}
保存文件的Util:
package edu.njcit.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
public class UpDownLoadUtil {
private static SimpleDateFormat simpleDateFormat;
private static final String FILE_SAVE_PATH="uploadfiles";
static {
simpleDateFormat = new SimpleDateFormat("yyyy" + File.separator + "MM"
+ File.separator + "dd" + File.separator + "HH");
}
/**
* 将文件保存到服务器端硬盘中
* @param request
* @param file Tomcat临时文件
* @param fileFileName 客户端实际文件名
* @return 保存好的服务器端的文件(路径+文件名(UUID))
* @throws IOException
*/
public static File saveFile(HttpServletRequest request, File file,
String fileFileName) throws IOException {
if (file==null) {
return null;
}
File destFile=null;
try {
InputStream is = new FileInputStream(file);
String bathpath = request.getSession().getServletContext()
.getRealPath(FILE_SAVE_PATH);
String basePathWithDate = bathpath+File.separator
+ simpleDateFormat.format(new Date());
File tempfile = new File(basePathWithDate);
if (!tempfile.exists()) {
tempfile.mkdirs();
}
// 获得文件的扩展名
String ext = fileFileName.substring(fileFileName.lastIndexOf("."));
// 通过UUID和扩展名生成全球唯一的文件名
String uuidNameWithExt = UUID.randomUUID() + ext;
destFile = new File(basePathWithDate, uuidNameWithExt);
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int length = 0;
while (-1 != (length = is.read(buffer))) {
os.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}
return destFile;
}
/**
* 将文件系统对于的全路径+文件名转化为前台HTML中SRC对应的路径
* @param absPathName 文件系统对于的全路径+文件名
* @return
*/
public static String convertAbsPathToImgSrc(String absPathName) {
int start=absPathName.indexOf(FILE_SAVE_PATH) - 1;
//转换文件分隔符后的服务器端路径+文件名
String serverPath=absPathName.replace(File.separatorChar, '/');
//文件相对/WebRoot的路径
String src=serverPath.substring(start);
return src;
}
}
上传完了后,跳转到结果页面:
文件上传成功:<br/>
<p>struts2标签:</p>
原文件名: <s:property value="upLoadFile.originalName"/><br/>
保存到服务器端的位置: <s:property value="upLoadFile.serverDiskPathName"/><br/>
HTML访问的路径: <s:property value="upLoadFile.imgSrc"/><br/>
文件大小: <s:property value="upLoadFile.size"/><br/>
保存时间: <s:property value="upLoadFile.date"/><br/>
<p>EL表达式:</p>
原文件名: ${upLoadFile.originalName}<br/>
保存到服务器端的位置: ${upLoadFile.serverDiskPathName}<br/>
HTML访问的路径: ${upLoadFile.imgSrc}<br/>
文件大小: ${upLoadFile.size}<br/>
保存时间: <fmt:formatDate value="${upLoadFile.date}" type="both" pattern="yyyy-MM-dd HH:mm:ss" /><br/>
最后还差一个struts的配置,如下:
<package name="mydefault" extends="struts-default">
<action name="uploadFile" class="edu.njcit.action.updown.UpDownAction">
<result name="success">/downloadfile.jsp</result>
</action>
</package>
关于上传文件的大小可以在src目录下新建一个struts.properties文件进行配置:
#This file conf will overwrite the struts2-core-2.1.8.1.jar->org.apache.struts2->defalut.properties
#The priority of This file is over than the struts.xml constant
#struts.devMode=false
#struts.configuration.xml.reload=false
#upload file temp save dir
#struts.multipart.saveDir=
#1024*1024*3=3M=3145728
struts.multipart.maxSize=3145728