Struts(9)Struts的文件上传和下载及UUID类的使用

本文介绍如何使用Struts框架实现文件的上传与下载功能,包括表单配置、Action处理逻辑、文件重命名及中文文件名的支持等关键步骤。

1 上传下载原理

  • 上传:
    这里写图片描述

2 文件上传

①编写register.jsp

如果表单中有文件控件,则需要重新指定表单的编码方式enctype=”multipart/form-data”

<body>
<h1>注册用户</h1>
<!-- 如果表单中有文件控件,则需要重新指定表单的编码方式 -->
<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>
</body>

②编写UserForm表单

上传中有文件,所以myphoto类型为FormFile

public class UserForm extends ActionForm {
    private String name;
    private FormFile myphoto;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public FormFile getMyphoto() {
        return myphoto;
    }
    public void setMyphoto(FormFile myphoto) {
        this.myphoto = myphoto;
    }
}

③编写Action类,上传文件

public class RegisterAction extends Action {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        UserForm userForm = (UserForm) form;// TODO Auto-generated method stub

        String name = userForm.getName();
        FormFile formFile = userForm.getMyphoto();

        // 通过formFile可以获取用户上传文件的各种信息
        String filename = formFile.getFileName();
        int filesize = formFile.getFileSize();

        InputStream is = null;
        OutputStream os = null;
        try {
            // 获取输入流
            is = formFile.getInputStream();
            // 得到file文件夹,在服务器中的绝对路径
            String filepath = this.getServlet().getServletContext().getRealPath("/files");

            os = new FileOutputStream(filepath+"\\"+MyTools.getNewFileName(filename));
            // 读取文件并写到服务器files下
            int len = 0;
            // 做一个缓存
            byte []bytes = new byte[1024];
            while((len=is.read(bytes))>0) {
                // 将读到的数据写入到files
                os.write(bytes, 0, len);
            }

            // TODO 在这里保存到数据库即可(本次未使用,因此在获取文件列表时采用获取文件夹下所有文件的办法)

        } catch (Exception e) {
            e.printStackTrace();
            return mapping.findForward("err");
        } finally {
            try {
                is.close();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        System.out.println(filename + " " + filesize);

        return mapping.findForward("ok");
    }
}

④文件重名覆盖问题

编写工具类,生成一个不重复的文件名

public class MyTools {
    public static String getNewFileName(String filename) {
        String uuid = UUID.randomUUID().toString();
        int beginIndex = filename.lastIndexOf(".");

        String newfilename = uuid+filename.substring(beginIndex);

        return newfilename;
    }
    public static String getFileName(String fName) {
        fName = fName.trim();
//        String fileName = fName.substring(fName.lastIndexOf("/")+1);  
        //或者  
        String fileName = fName.substring(fName.lastIndexOf("\\")+1);  
        return fileName;
    }
    public static ArrayList<String> getFiles(String path) {
        ArrayList<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
//              System.out.println("文     件:" + tempList[i]);
                files.add(MyTools.getFileName(tempList[i].toString()));
            }
            if (tempList[i].isDirectory()) {
//              System.out.println("文件夹:" + tempList[i]);
            }
        }
        return files;
    }
}

⑤中文标题文件上传失败问题

使用过滤器:http://blog.youkuaiyun.com/u013943420/article/details/71036669#t7

3 文件下载

①下载时,需要显示文件名称、上传人名,因此需要将信息保存到数据库中。

②展示已上传文件

public class UserListAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        String path = this.getServlet().getServletContext().getRealPath("/files");
        // 准备用户列表数据(从数据库获取,本次未使用)
        ArrayList<String> files = MyTools.getFiles(path);

        request.setAttribute("userlist", files);

        return mapping.findForward("showUsers");
    }
}

showUserList.jsp显示文件列表

<body>
  <h1>用户列表</h1> <br>
  <c:forEach items="${userlist}" var="filename">
  ${filename}<img src="/StrutsFileupAndDown/files/${filename}" width="50px" /><a href="/StrutsFileupAndDown/downloadFile.do?filename=${filename }">点击下载</a><br>
  </c:forEach>
</body>

③编写Action,下载文件

public class DownloadFileAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {

        String filename = request.getParameter("filename");

        response.setContentType("text/html;charset=utf-8");
        // 设置Response头,告诉浏览器有文件下载(如果文件名有中文,需要对其进行url编码)
        String filterFilename;
        try {
            filterFilename = URLEncoder.encode(filename, "utf-8");
            response.setHeader("Content-Disposition", "attachment; filename="+filterFilename);
        } catch (Exception e1) {
            e1.printStackTrace();
        }


        // 获取下载文件的绝对路径
        String filepath = this.getServlet().getServletContext().getRealPath("/files");
        String fileFullPath = filepath + "\\" + filename;

        FileInputStream fis = null;
        OutputStream os = null;
        byte []buffer = new byte[1024];
        int len = 0;
        try {
            fis = new FileInputStream(fileFullPath);
            os = response.getOutputStream();

            while((len=fis.read(buffer))>0) {
                os.write(buffer, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        System.out.println(filepath + filename);
        // 返回文件列表jsp页面
        return mapping.findForward("goback");
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ADreamClusive

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值