获取表单文件,并保存在本地(Servlet)

来源:互联网 发布:mysql未识别的服务 编辑:程序博客网 时间:2024/06/02 05:11

jsp文件信息

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title>*图片上传*</title>  </head>    <body>    <form action="<%=path %>/servlet/UserPhotoSer" enctype="multipart/form-data" method="post">        <input type="text" name="type" value="0" style="display: none;" />        <table>            <tr>                <td>账号:<input type="text" name="account" /></td>            </tr>            <tr>                <td>选择照片:<input type="file" name="file1" /></td>            </tr>            <tr>                <td><input type="submit" value="提交"/></td>            </tr>        </table>    </form>  </body></html>

Servlet代码

    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8"); // 设置编码        // 获得磁盘文件条目工厂        DiskFileItemFactory factory = new DiskFileItemFactory();                //判断图片的存放位置        String HCpath = this.getServletContext().getRealPath("/uploads/upgoods");        // 如果没以下两行设置的话,上传大的 文件 会占用 很多内存,        // 设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同        /**         * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem         * 格式的 然后再将其真正写到 对应目录的硬盘上         */        factory.setRepository(new File(HCpath));        // 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室        factory.setSizeThreshold(1024 * 1024);        // 高水平的API文件上传处理        ServletFileUpload upload = new ServletFileUpload(factory);        try {            // 可以上传多个文件            List<FileItem> list = (List<FileItem>) upload.parseRequest(request);            for (FileItem item : list) {                // 获取表单的属性名字                String name = item.getFieldName();                // 如果获取的 表单信息是普通的 文本 信息                if (item.isFormField()) {                    // 获取用户具体输入的字符串 ,名字起得挺好,因为表单提交过来的是 字符串类型的                    String value = item.getString();                    request.setAttribute(name, value);                }                // 对传入的非 简单的字符串进行处理 ,比如说二进制的 图片,电影这些                else {                    //也给用用以下方法获取原文件的名称+后缀//                    //获取路径名  //                    String value = item.getName() ;  //                    //索引到最后一个反斜杠  //                    int start = value.lastIndexOf("\\");  //                    //截取 上传文件的 字符串名字,加1是 去掉反斜杠,  //                    String filename = value.substring(start+1);                                                              System.out.println("获取上传文件的总共的容量:" + item.getSize());                    if(item.getSize() == 0){                        System.out.println("未选择图片");                        request.setAttribute("imageUrl", "图片错误,可能未选择图片");                        break;                    }                    String path = null;                    int type = Integer.parseInt((String) request.getAttribute("type"));                    String imageUrl=null;                    //根据获取的种类不同存放不同的文件夹路径                    switch (type) {                    case 0: imageUrl = "/images/uploads";path = this.getServletContext().getRealPath(imageUrl);break;                    case 1: imageUrl = "/images/upgoods";path = this.getServletContext().getRealPath(imageUrl);break;                    case 2: imageUrl = "/images/upusers";path = this.getServletContext().getRealPath(imageUrl);break;                    default:path = this.getServletContext().getRealPath("/images/uploads");break;                    }                    //获取账号                    String account = (String) request.getAttribute("account");                    System.out.println(account);                    //获取当前时间                    Date now = new Date();                    //设置时间的格式                    SimpleDateFormat dateFormat = new SimpleDateFormat(                            "yyyyMMddHHmmss");                    String fileTime = dateFormat.format(now);                    System.out.println(fileTime);                    //设置文件的名称为 账号+时间+.jpg                    String filename = account + fileTime + ".jpg";                    request.setAttribute(name, filename);                    String Urlpath = request.getContextPath();                    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+Urlpath;                    request.setAttribute("imageUrl", basePath+imageUrl+ "\\"+filename);                    // 真正写到磁盘上                    // 它抛出的异常 用exception 捕捉                    // item.write( new File(path,filename) );//第三方提供的                    // 手动写的                                        OutputStream out = new FileOutputStream(new File(path,                            filename));                    InputStream in = item.getInputStream();                    int length = 0;                    byte[] buf = new byte[1024];////                    System.out.println("获取上传文件的总共的容量:" + item.getSize());//                    if(item.getSize() == 0){//                        System.out.println("未");//                        break;//                    }                    // in.read(buf) 每次读到的数据存放在 buf 数组中                    while ((length = in.read(buf)) != -1) {                        // 在 buf 数组中 取出数据 写到 (输出流)磁盘上                        out.write(buf, 0, length);                    }                    in.close();                    out.close();                }            }        } catch (FileUploadException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (Exception e) {            // TODO Auto-generated catch block            // e.printStackTrace();        }         request.getRequestDispatcher("/return_Info/imageUrl.jsp").forward(request,response);    }



0 0
原创粉丝点击