Servlet3文件单个和多个文件上传

Servlet3文件单个和多个文件上传

8888.gif-381.5kB

Servlet3.0提供了对文件上传的支持,通过@MultipartConfig 标注和HttpServletRequest的两个新方法getPart()和getParts(),开发者能够很容易实现文件的上传操作。

 <body>

  <!-- 
        表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,
        这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,
        才能完整的传递文件数据,进行下面的操作.
        enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去

   -->
        <form action="update" method="post" enctype="multipart/form-data">
            <fieldset>
                <legend>单文件上传</legend>
                <input type="file" name="photo">
                <input type="submit" value="上传">
            </fieldset>

            <fieldset>
                <legend>多文件上传</legend>
                <input type="file" name="pic">
                <input type="file" name="pic">
                <input type="file" name="pic">
                <input type="file" name="pic">
                <input type="submit" value="上传">
            </fieldset>

        </form>
  </body>

image_1c3lh33se1roe1sjubil1btaihp9.png-30.6kB

servlert通过part读写图片


@WebServlet(
        urlPatterns="/update" //设置servlet的路径
        )
@MultipartConfig  //Servlet希望处理的请求时multipart/form-data类型的
public class FileUpdate extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        //设置为接收文件名的格式编码格式
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        mutiFileUpload(req);

        req.getRequestDispatcher("/index.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    //过滤part.header得到文件名称
    private static String getFileName(String disp){

        /*ie 用于ie游览器
        String str = "form-data; name=\"photo\"; filename=\"C:"+File.separator+"Users"+File.separator+"Administrator"+File.separator+"Desktop"+File.separator+"xxx.png\"";
        */


        /*   
         * goole 和 fixfox游览器
         * String str = "form-data; name=\"photo\"; filename=\"xxx.png\"";  
         */

        String[] s = disp.split("=");



        //得到"C:\Users\Administrator\Desktop\xxx.png" 和"xxx.png"
        String st = s[2];
        int lastSep =st.lastIndexOf(File.separator)  ;
        int lastIndex = st.lastIndexOf("\"");

        //当没有File.separator时,获取lastSep=1,其它为lastSep+1
        lastSep=lastSep==-1 ? lastSep=1:lastSep+1;

        String fileName = st.substring(lastSep,lastIndex);


        return fileName;

    }


    //(单)多文件上传
     private static void mutiFileUpload(HttpServletRequest req){
         String fileName="";
         Collection<String> list = new ArrayList<String>();

        try {
            //接收多个或者单个的图片
            Collection<Part>  parts = req.getParts();

            for(Part part:parts){
                String head = part.getHeader("content-disposition");
                fileName = getFileName(head);

                //避免中间的文件为空,导致无法写入接收到文件
                if(fileName == null || fileName.equals("")){
                    continue;
                }

                String path = req.getServletContext().getRealPath(File.separator+"img");


                //String path = "E:"+File.separator+"imges";
                //写入文件
                part.write(path+File.separator+fileName);
                list.add("img"+File.separator+fileName);


            }

            req.setAttribute("list", list); 


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

显示页面

<body>




         <c:forEach items="${list }" var="per" varStatus="status">

            <img alt="" src="<c:out value="${per }"></c:out>" width="300px" height="300px"> 

         </c:forEach>




  </body>

当接收文件为中文名称时,使用的Tomcat7.x版本时要设置编码格式为utf-8,否则无法显示图片

image_1c3ncsfq6129vcq81nlhqkml152b.png-14.8kB

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值