Struts 1.3中实现文件的上传与下载

来源:互联网 发布:蜂窝移动网络设置 编辑:程序博客网 时间:2024/05/19 19:58

本文记录的是我写的一个用struts 1.3实现的文件上传和下载的例子

由于各种文件都可能被上传或者下载,所以输入流使用字节流而不是字符流。字符流只用于文本文件。



①建立web工程,引入struts开发包

②写register.jsp(有文件传输,表单提交只能用post)

如果我们的表单有文件这样的控件,则需要重新指定表单的编码方式

<form enctype="multipart/form-data" action="/strutsfileupanddown/register.do" method="post">    名字:<input type="text" name="name"><br/>    头像:<input type="file" name="myphoto"><br/>    <input type="submit" value="提交" /></form>

③写Action和ActionForm(不能使用动态表单)

④在ActionForm中,对应表单中file的属性为FormFile数据类型

⑤牵线,写业务逻辑

文件上传核心代码:

InputStream is = null;OutputStream os = null;try {//取出输入流is = formFile.getInputStream();//得到输出流 -> 文件//1. 得到file文件夹的上传到tomcat服务器后的绝对路径String keepFilePath = this.getServlet().getServletContext().getRealPath("/file");System.out.println("keepFilePath="+keepFilePath);os = new FileOutputStream(keepFilePath+"\\"+fileName);//读取文件并写到服务器fileint len = 0;//做一个缓存bufferbyte [] bytes = new byte[1024];//循环处理while((len=is.read(bytes))>0){//读一点,写一点os.write(bytes, 0, len);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{try {is.close();os.close();} catch (Exception e2) {// TODO: handle exception}

解决文件上传的细节问题:

1. 中文名字的文件

使用过滤器,解决中文乱码问题

2. 文件覆盖问题

利用UUID类产生伪随机数作为文件名

public static String getNewFileName(String fileName){int beginIndex = fileName.lastIndexOf(".");String newFileName = UUID.randomUUID().toString() + fileName.substring(beginIndex, fileName.length());return newFileName;}

文件下载核心代码:

//获取用户名String username = request.getParameter("user");//获取Register对象RegisterService rs = new RegisterService();Register r = rs.getRegister(username);response.setContentType("text/html;charset=utf-8");//如果文件名有中文,需要对其进行URL编码String filterFilename = "";try {filterFilename = URLEncoder.encode(r.getPhotoNameOld(),"utf-8");} catch (UnsupportedEncodingException e1) {// TODO Auto-generated catch blocke1.printStackTrace();} //设置一个头,告诉浏览器有文件要下载response.setHeader("Content-Disposition", "attachment; filename="+filterFilename);//下载文件//1.先获取要下载文件的绝对路径String filePath = this.getServlet().getServletContext().getRealPath("/file");//文件全路径String fileAllPath = filePath + "\\" + r.getPhoteNameNew();FileInputStream fis = null;OutputStream os = null;//定义缓存byte [] buffer = new byte[1024];int len = 0;try {fis = new FileInputStream(fileAllPath);os = response.getOutputStream();while((len = fis.read(buffer))>0){os.write(buffer, 0, len);}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{try {os.close();fis.close();} catch (Exception e2) {// TODO: handle exceptione2.printStackTrace();}}return null;}


在下载的Action中,应该return null,不然会有getOutputStream() has already been called forthis response异常抛出。

在下载的页面,应该这样写:

<tr><td>${user.username }</td><td><img width="50px" src="/strutsfileupanddown/file/${user.photeNameNew}"></td><td>${user.photoNameOld }</td><td><a href="/strutsfileupanddown/downLoadFile.do?user=${user.username }">下载</a></td></tr>