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

来源:互联网 发布:淘宝确认收货前换货 编辑:程序博客网 时间:2024/05/19 04:04

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.csdn.net/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");    }}
0 0
原创粉丝点击