您的位置:首页 > 编程语言 > Java开发

用struts1.x实现文件上传、下载(文件存在文件系统中)

2009-08-06 18:36 776 查看
一、上传

1. JSP

<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>

<html:form action="upload.do" method="post" enctype="multipart/form-data">

<html:file property="file"></html:file>

<html:submit>上传</html:submit></html:form>

2. ActionForm类有FormFile属性

3. Action类

FileForm fileform=(FileForm)form;
FormFile file=fileform.getFile();
String filename=file.getFileName();
InputStream is=file.getInputStream();
String basePath=this.getServlet().getServletContext().getRealPath("/");
OutputStream os=new FileOutputStream(basePath+"upload/"+filename);
byte[] b=new byte[is.available()];
is.read(b);
os.write(b);
is.close();
os.flush();
os.close();

二、下载

//contentDisposition为要添加的数据。如果contentDisposition为null,则组件将自动添加"attachment;",以表明将下载的文件作为附件,结果是IE浏览器将会提示另存文件,而不是自动打开这个文件(IE浏览器一般根据下载的文件扩展名决定执行什么操作,扩展名为doc的将用word程序打开,扩展名为pdf的将用acrobat程序打开,等等)。

response.setContentType("application/x-msdownload");
String filename=request.getParameter("filename");
response.setHeader("Content-Disposition","attachment;"+"filename="+new String(filename.getBytes(), "ISO-8859-1"));
InputStream is=new FileInputStream("E:/tomcat6/webapps/smallweb/upload/"+filename);
byte[] b=new byte[is.available()];
is.read(b);
OutputStream os=response.getOutputStream();
os.write(b);
os.flush();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: