文件上传:
upload.jsp表单:
1):表单必须使用POST方式提交;
2):使用二进制编码:multipart/form-data
3):;
用户名:
文件:
Struts2底层使用的是Apache的上传组件(commons-fileupload-1.3.1.jar)实现文件的上传
Struts2文件上传的细节:
Struts2中的FileUploadInterceptor拦截器完成了文件上传设置操作:
struts2.xml:
1048576
jpg,gif
/success.jsp
/upload.jsp
action:
public class FileUpLoadAction extends ActionSupport{
private String username;
//命名框架固定格式 对应file表单的name值
private File myUpload; //上传的文件
private String myUploadFileName; //上传的文件名
private String myUploadContentType; //上传的文件类型 -- image/jpeg
public String upload() throws IOException {
//直接保存到磁盘中
//将文件保存到当前/upload文件夹中
//获取到指定相对路径对应的绝对路径。
String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
System.out.println(realPath);
//构建一个目标文件,将数据拷贝到目标文件中
File destFile = new File(realPath,myUploadFileName);
FileUtils.copyFile(myUpload, destFile);
return SUCCESS;
}
//getter/setter
}
文件下载:
Struts2提供 stream 结果类型,专门用于支持文件下载功能的。
属性修参考 struts-default.xml中 stream 拦截器
contentType: 指定被下载文件的文件类型;
inputName: 指定被下载文件的入口输入流;
contentDisposition: 指定下载的文件名;
bufferSize: 指定下载文件时的缓冲大小。
表单:
Insert title here
资源下载
资源1
资源2
struts2.xml:
inputStream
attatchment;filename=${filename}
action:
package cn.com.my;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadAction extends ActionSupport{
private String filename;
private File file;
public String download() {
//根据传递来的文件名找到对应的文件。
String realPath = ServletActionContext.getServletContext().getRealPath("/WEB-INF/download");
System.out.println(filename);
System.out.println(realPath);
file = new File(realPath,filename);
//将找到的文件响应到浏览器弹出下载页面 下载
//返回值不应该对应一个物理地址(不是简单页面跳转)
return SUCCESS;
}
//给struts2框架调用, 将获取到要下载的文件数据响应给浏览器
public InputStream getInputStream() throws Exception {
return new FileInputStream(file);
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
}