javaweb 前端多文件传送、后端文件处理

例子

前端jsp

<body>
<!--action指的是这个表单要提交到哪里  -->
<!--method指的是这个表单用什么方式提交  -->
<!--enctype="multipart/form-data"    必须要,不可少 -->
<form id="form" action="upload.do" method="post" enctype="multipart/form-data" >
<!--注释  -->
文件:<input type="file" name="fileinput" multiple="multiple" />
<input type="submit" value="提交"  />
<br>
</form>
</body>

后台

@MultipartConfig
public class FileUpload extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse response)
            throws ServletException, IOException {
        Collection<Part> parts=req.getParts();//重点,多文件所以Part要是个数组
        InputStream is=null;
        FileOutputStream fos=null;
        for(Part p:parts){
            String s=p.getHeader("content-disposition");//重点、获取文件名
            String filename=s.substring(s.indexOf("filename=\"")+"filename=\"".length(),s.length()-1);
             
            is=p.getInputStream();
            File file=new File("d:\\"+filename);//存放文件的地址
            fos=new FileOutputStream(file);
            
            byte[] b=new byte[1024];
            int bcount=0;//最后读取到哪里
            bcount=is.read(b);
            while(bcount!=-1){
                fos.write(b,0,bcount);
                bcount=is.read(b);
            }
            fos.flush();
        }
        
        //迭代器循环
        /*Iterator<Part> it=parts.iterator();
        while(it.hasNext()){
            Part p=it.next();
            parts.add(p);
        }*/
        is.close();
        fos.close();
        
        //设置request的编码
        req.setCharacterEncoding("utf-8");
        //设置response的编码
        response.setCharacterEncoding("GBK");
        //页面跳转到/page/form-file-submit.jsp
        req.getRequestDispatcher("/page/form-file-submit.jsp").forward(req, response);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值