Struts上传和下载
一、文件单个上传fileupload.jar
1.upload.jsp,注意enctype="multipart/form-data",type="file"
1 <form action="upload.action" method="post" enctype="multipart/form-data"> 2 上传文件: 3 <input type="file" name="file" /> 4 <input type="submit" value="上传" /> 5 </form>
2.UploadAction
public class UploadAction { private File file; private String fileFileName;// 前台界面 name名 + FileName ,才能获取文件名 public String getFileFileName() { return fileFileName; } public void setFileFileName(String fileFileName) { this.fileFileName = fileFileName; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public String execute() throws Exception{ InputStream is = new FileInputStream(file); String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload"); File toFile = new File(uploadPath, this.getFileFileName()); OutputStream os = new FileOutputStream(toFile); byte[] buffer = new byte[1024*5]; int length = 0; while ((length = is.read(buffer)) > 0) { os.write(buffer, 0, length); } is.close(); os.close(); return "success"; } }
二、多文件批量上传、使用swfupload
1.IType上有一篇博客,讲解的很好,链接如下:
http://hanxin0311.iteye.com/blog/1915611
三、文件的下载
Struts2提供了stream结果类型,该结果类型专门用于支持文件下载的功能。当指定stream结果类型时,需要配置一个inputName参数,该参数指定了一个输入流,这个输入流是被下载文件的入口(即通过该入口才能实现文件以流的方式实现下载)。
实现文件下载的Action
public class DownloadSongAction { //获取下载文件名 public String getDownloadFileName() { return downloadFileName; } //实现下载的Action类应该提供一个返回InputStream实例的方法 public InputStream getInputStream() throws UnsupportedEncodingException{ } //处理用户请求 public String execute(){ } }
对应的struts.xml
<action name="downloadsong" class="cn.edu.cqu.cqzy.action.DownloadSongAction"> <result name="success" type="stream"> <param name="contentType">application/octet-stream;charset=UTF-8</param> <param name="contentDisposition">attachment;filename="${downloadFileName}"</param> <param name="inputName">inputStream</param> <param name="bufferSize">4096</param> </result> <result name="fail">/jsp/login.jsp</result> <result name="authorityfail">/jsp/yxk.jsp</result> </action>