一、文件的上传
// io流
String realPath = ServletActionContext.getServletContext().getRealPath("\\upload");
// 输入流读取文件
FileInputStream inputStream = new FileInputStream(file);
// 创建一个文件对象
File targetr = new File(realPath, fileFileName);
// 创建一个输出流
FileOutputStream outputStream = new FileOutputStream(targetr);
byte[] bb = new byte[1024];
int len;
while ((len = inputStream.read(bb)) != -1) {
outputStream.write(bb, 0, len);
}
outputStream.close();
inputStream.close();
Struts2中的文件上传
public String upload() throws IOException {
// io流
String realPath = ServletActionContext.getServletContext().getRealPath("\\upload");
// 创建一个文件对象
File targetr = new File(realPath, fileFileName);
FileUtils.copyFile(file, targetr);
return SUCCESS;
}
文件上传过滤器的设置
<!-- 添加文件上传拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 设置允许上传的文件类型 -->
<param name="allowedTypes">
image/jpeg,image/bmp
</param>
<!-- 设置允许上传的文件大小 -->
<param name="maximumSize">81920</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"/>
二、文件的下载
// 获取到要下载资源
String realPath = ServletActionContext.getServletContext().getRealPath("\\download\\abc.txt");
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
// 设置响应头
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
response.setHeader("Content-disposition", "attachment;fileName=" + filename);
// 输入流
FileInputStream inputStream = new FileInputStream(realPath);
// 输出流
ServletOutputStream outputStream = response.getOutputStream();
byte[] bb = new byte[1024];
int len;
while ((len = inputStream.read(bb)) != -1) {
outputStream.write(bb, 0, len);
}
outputStream.close();
inputStream.close();
struts2中的文件下载
public String streamDownLoad() throws IOException{
// 获取到要下载的资源 的路径
String realPath = ServletActionContext.getServletContext().getRealPath("\\download\\abc.txt");
setInputStream(new FileInputStream(realPath));
fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
return Action.SUCCESS;
}