文件上传和文件下载是我们在web应用程序中常用的两个功能,在java中,实现这两种功能的方式也有很多种,其中struts2就给我们提供了一种算是比较简单的方式吧,下面我们就一起来看一下,首先我们来看文件上传:
文件上传
文件上传我们首先应该注意的是在上传页面的表单,这个表单也是有讲究的,由于我们提交表单的数据中有文件上传,所以这个表单的所使用的编码类型就不能是原来的了,在这里我们应该使用的编码方式是multipart/form-data,并且数据提交方式要用post方式,下面我们具体来看一下:
upload.jsp
!--在进行文件上传时,表单提交方式一定要是post的方式,因为文件上传时二进制文件可能会很大,还有就是enctype属性,这个属性一定要写成multipart/form-data,
不然就会以二进制文本上传到服务器端-->
<body>
<s:fielderror></s:fielderror>
<form action="upload.action" method="post" enctype="multipart/form-data">
file: <input type="file" name="file"><br>
<input type="submit" value="submit">
</form>
</body>
看完表单以后我们就要来看一下action里面是怎么来接收这些数据的,其实也很简单,直接在action中定义三个变量,这三个变量分别是文件、文件名,还有文件类型,如下:
private File file; // 注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
private String fileFileName;// 提交过来的file的名字
private String fileContentType;// 提交过来的file的MIME类型
这三个变量的名字是有讲究的,不是随便命名就OK了,其中file这个变量名要和表单中文件的name要相同,fileFileName这个也是固定的,起名格式就是name+FileName,同样fileContentType也是如此,命名规则是name+ContentType,只有你按照命名规则来定义变量,struts2才能把文件上传相关信息收集起来。
fileUploadActon.java:
package com.lft.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport {
private File file; // 注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
private String fileFileName;// 提交过来的file的名字
private String fileContentType;// 提交过来的file的MIME类型
private String savePath; // 上传文件保存的 路径
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
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 String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
@Override
public String execute() throws Exception {
/*还可以通过import org.apache.commons.io.FileUtils;
FileUtils.copyFile(file, new File(root, fileFileName))调用该
方法可以直接完成文件的上传。
*/
String root = ServletActionContext.getServletContext().getRealPath(
savePath);
InputStream is = new FileInputStream(file);
OutputStream os = new FileOutputStream(new File(root, fileFileName));
System.out.println("fileFileName: " + fileFileName); // 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
System.out.println("file: " + file.getName());
System.out.println("file: " + file.getPath());
byte[] buffer = new byte[500];
int length = 0;
while (-1 != (length = is.read(buffer, 0, buffer.length))) {
os.write(buffer);
}
os.close();
is.close();
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("file", fileFileName);
return SUCCESS;
}
}
FileDownAction.java
package com.lft.action;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownAction extends ActionSupport{
private String downloadFileName;
public String getDownloadFileName() throws UnsupportedEncodingException {
String fileName=ServletActionContext.getRequest().getParameter("fileName");
System.out.println(fileName);
this.downloadFileName = fileName;
System.out.println(downloadFileName);
return downloadFileName;
}
public InputStream getDownloadFile() throws FileNotFoundException, UnsupportedEncodingException
{
String fileName = getDownloadFileName();
String root = "/upload/"+fileName;
System.out.println(root);
// 如果下载文件名为中文,进行字符编码转换
ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="
+ java.net.URLEncoder.encode(fileName, "UTF-8"));
InputStream inputStream =ServletActionContext.getServletContext().getResourceAsStream(root);//使用绝对路径 ,从该路径下载“测试.txt"文件
System.out.println(inputStream);
return inputStream;
}
@Override
public String execute() throws Exception
{
return SUCCESS;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <constant name="struts.devMode" value="false" /> <constant name="struts.i18n.encoding" value="UTF-8"></constant> <constant name="struts.custom.i18n.resources" value="messages_zh_CN" /> <package name="default" namespace="/" extends="struts-default"> <action name="upload" class="com.lft.action.FileUploadAction"> <!-- 配置fileUpload的拦截器 --> <interceptor-ref name="fileUpload"> <param name="allowedTypes">image/png,image/gif,image/jpeg</param><!-- 配置允许上传的文件类型 --> <!--maximumSize (可选) - 这个拦截器允许的上传到action中的文件最大长度(以byte为单位). 9 注意这个参数和在webwork.properties中定义的属性没有关系,默认2MB--> <param name="maximumSize">10240000</param><!-- 配置允许上传的文件大小 --> </interceptor-ref> <!-- 配置系统默认的拦截器 --> <interceptor-ref name="defaultStack"></interceptor-ref> <param name="savePath">/upload</param> <result name="success">/index.jsp</result> <result name="input">/upload.jsp</result> </action> <action name="download" class="com.lft.action.FileDownAction"> <result name="success" type="stream"> <param name="contentDisposition">attachment;filename="${downloadFileName}"</param> <param name="inputName">downloadFile</param> </result> </action> </package> </struts>
index.jsp
<body>
<s:form>
<div style="border:1px solid black">成功上传的文件:<br>
<a href="download.action?fileName=<s:property value="#request.file"/>">下载此图片</a>
</div>
</s:form>
</body>
messages_zh_CN.properties
#更改上传文件类型不允许的提示信息 struts.messages.error.content.type.not.allowed=\u6587\u4ef6\u4e0a\u4f20\u5931\u8d25\uff1a\u4f60\u8981\u4e0a\u4f20\u7684\u6587\u4ef6\u7c7b\u578b\u4e0d\u5141\u8bb8 #更改上传文件太大的提示信息 struts.messages.error.file.too.large=\u6587\u4ef6\u4e0a\u4f20\u5931\u8d25\uff1a\u4f60\u8981\u4e0a\u4f20\u7684\u6587\u4ef6\u592a\u5927 #文件上传其它错误信息 struts.messages.error.uploading=\u6587\u4ef6\u4e0a\u4f20\u5931\u8d25\uff1a\u53d1\u751f\u5185\u90e8\u9519\u8bef
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>