首先详细讲一下文件上传部分
<form id="form" action="Upload!uploads.action" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="button" onclick="tijiao()" value="提交"> </form>
以上是一个简单的文件上传表单,需要注意的是enctype="multipart/form-data"这个属性必须加上,表明以二进制的数据格式来传输数据
上传的Action中可以这么写
private File file;//用此属性接收页面表单的file值 private String fileFileName;//此处的文件名必须是表单file name+FileName private String types; private IfileService service; private String commonTypes; @Override public String execute() throws Exception { String path=ServletActionContext.getRequest().getRealPath("/upload"); File fi= new File(path); if(!fi.exists()) fi.mkdir(); FileOutputStream os=new FileOutputStream(path+"/"+fileFileName); byte buffer[]=FileToByte.getBytesFromFile(file); os.write(buffer); os.close(); return "success"; }
以上就实现文件上传了,文件下下载也很简单,贴代码吧
public InputStream getInputStream() { InputStream stream=ServletActionContext.getServletContext().getResourceAsStream( "/upload/" + fileName); return stream; } @Override public String execute() throws Exception { if(getInputStream()==null) { return INPUT; }else { return updateFileDownLoadCount(); } }
然后注意下Struts.xml中result的type类型
<action name="DownloadFileAction" class="DownloadFileAction"> <result type="stream"> <param name="bufferSize">2048</param><!-- 缓冲区大小 --> <param name="contentType">application/octet-stream;charset=ISO8859-1</param><!--告诉浏览器内容是文件流--> <param name="contentDisposition">attachment;fileName="${fileName}"</param> <!--获取下载文件名 --> </result> </action>