一、struts文件的上传
1.在表单中添加属性<s:form enctype="multipart/form-data" />
2.在实体类中定义用于文件上传的属性并生成get、set方法:
private String path; //存到数据库的文件路径名
private String fileName;//存到数据库的文件名
private File upload; //临时文件
private String uploadContextType; //文件类型
private String uploadFileName; //文件名
3、在struts.xml文件中定义拦截器:
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">20971520</param> <!-- 上传文件的最大值-->
<param name="fileUpload.allowedTypes">application/msword</param> <!-- 上传文件的类型-->
<param name="fileUpload.allowedExtensions">.doc</param> <!-- 上传文件的后缀名-->
</interceptor-ref>
4、在action中:
String path = ServletActionContext.getServletContext().getRealPath("/upload"); //得到路径名
File file = new File(path, user.getUploadFileName());
FileUtils.copyFile(user.getUpload(), file); //把临时文件复制到file中
user.getUpload().delete(); //删除临时文件
user.setPath(path); //设置路径
user.setFilename(user.getUploadFileName()); //设置文件名
userDao.saveUser(user); //保存到数据库中
二、struts文件的下载
1.在实体类中添加属性并生成get、set方法:
private InputStream inputStreamxxx;
2.在action中,获得对象后
FileInputStream fis = new FileInputStream(new File(ewUser.getPath,newUser.getFilename()));
newUser.setInputStreamxxx(fis);
return "download";
3、在struts.xml文件中:
<result name="download" type="stream">
<param name="contentType">application/x-msdownload</param>
<param name="inputName">inputStreamxxx</param>
<param name="contentDisposition">attachment;filename=${filename}</param>
<param name="bufferSize">1024</param>
</result>
1.在表单中添加属性<s:form enctype="multipart/form-data" />
2.在实体类中定义用于文件上传的属性并生成get、set方法:
private String path; //存到数据库的文件路径名
private String fileName;//存到数据库的文件名
private File upload; //临时文件
private String uploadContextType; //文件类型
private String uploadFileName; //文件名
3、在struts.xml文件中定义拦截器:
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">20971520</param> <!-- 上传文件的最大值-->
<param name="fileUpload.allowedTypes">application/msword</param> <!-- 上传文件的类型-->
<param name="fileUpload.allowedExtensions">.doc</param> <!-- 上传文件的后缀名-->
</interceptor-ref>
4、在action中:
String path = ServletActionContext.getServletContext().getRealPath("/upload"); //得到路径名
File file = new File(path, user.getUploadFileName());
FileUtils.copyFile(user.getUpload(), file); //把临时文件复制到file中
user.getUpload().delete(); //删除临时文件
user.setPath(path); //设置路径
user.setFilename(user.getUploadFileName()); //设置文件名
userDao.saveUser(user); //保存到数据库中
二、struts文件的下载
1.在实体类中添加属性并生成get、set方法:
private InputStream inputStreamxxx;
2.在action中,获得对象后
FileInputStream fis = new FileInputStream(new File(ewUser.getPath,newUser.getFilename()));
newUser.setInputStreamxxx(fis);
return "download";
3、在struts.xml文件中:
<result name="download" type="stream">
<param name="contentType">application/x-msdownload</param>
<param name="inputName">inputStreamxxx</param>
<param name="contentDisposition">attachment;filename=${filename}</param>
<param name="bufferSize">1024</param>
</result>