1、文件上传三种方式:
将文件以二进制的形式保存到数据库中 activiti工作流框架
将文件存储到专门文件服务器(存放文件用的Linux系统)中
直接将文件存储到服务器(tomcat所在服务器)中
2、文件上传的一个实例:
action里的代码如下
public class UploadAction extends BaseAction implements ModelDriven<Student>{
private File file;// xxx
private String fileContentType;// xxxContentType
private String fileFileName;// xxxFileName
private StudentDAO studentDao=new StudentDAO();
private Student student=new Student();
private String serverDir = "/upload";
public String upload() {
System.out.println(file);
System.out.println(fileContentType);
System.out.println(fileFileName);
System.out.println("============================");
String realPath = getRealPath(serverDir + "/" + fileFileName);
System.out.println(realPath);
// 参数1:本地文件
// 参数2:tomcat服务器文件
try {
FileUtils.copyFile(file, new File(realPath));
} catch (IOException e) {
e.printStackTrace();
}
return SUCCESS;
}
/**
* 获取Linux目录的真实路径
* @param string 指的是本地路径(相对于工程WebContent所在的路径)
*/
private String getRealPath(String path) {
return appliaction.getRealPath(path);
}
jsp页面的代码如下:
<form action="${pageContext.request.contextPath }/sy/uploadAction_upload.action" enctype="multipart/form-data" method="post">
<input type="file" name="file">
<input type="submit" value="上传">
</form>
3、文件下载的一个实例:
action里的代码如下:
public String openAs() {
String type = "image/jpeg";
String name = "IMG_0933.JPG";
response.setContentType(type);
response.setHeader("Content-Disposition","filename=" + name);//文件名
/*
* 从服务器拿图片到本地
* 源:服务器
* 目的:jsp输出图片
*/
File serverFile = new File(getRealPath(serverDir + "/" + name));
try {
FileUtils.copyFile(serverFile, response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
jsp页面的代码如下:
<h2>直接展示</h2>
<s:url var="openAsUrl" namespace="/sy" action="uploadAction_openAs"></s:url>
---
<img alt="" src='<s:property value="#openAsUrl"/>'>
处理文件名的中文乱码:
String fileName = d.getFileName();
fileName = new String(fileName.getBytes(“utf-8”), “iso8859-1”);
struts2文件上传大小设置:
struts2文件上传类型设置(通过配置拦截器):
根据struts2自带的fileupload拦截器中提供的allowedTypes来进行限制
image/png,image/gif,image/jpeg