Servlet 实现文件上传

Servlet 实现文件上传需要 commons-fileupload-1.2.2.jar
,解析上传的二进制数据。

表单需要修改enctype属性值为 multipart/form-data,提交方法为post 。上传文件要使用文件域(<input type="file" >)。

<form action="..." method="post" enctype="multipart/form-data">
    <input type="file">
    <input type="submit value="上传文件">
</form>

Servlet 类的doPost() 方法:

        response.setCharacterEncoding("UTF-8");

        File file = null;
        String description1 = null, description2 = null;

        DiskFileUpload diskFileUpload = new DiskFileUpload();
        try {
            // 解析请求中的文本域和上传的文件,并装入 list 
            List<FileItem> list = diskFileUpload.parseRequest(request);
            for(FileItem item:list) {
                // 判断是否为文件
                if(!item.isFormField()) {
                    // 获取上传的文件名,创建一个新文件
                    File remoteFile = new File(new String(item.getName().getBytes(),"UTF-8"));

                    //System.out.println(remoteFile.getName());
                    //System.out.println(remoteFile.getAbsolutePath());
                    // 上传的文件不为空
                    if(!remoteFile.getName().equals("")) {
                        // 创建一个和上传文件名称一样的文件
                        //System.out.println(this.getServletContext().getRealPath("upload")); //上傳的路徑
                        file = new File(this.getServletContext().getRealPath("upload"),remoteFile.getName());
                        //System.out.println(file.getParentFile().getName());
                        file.getParentFile().mkdirs();  // 创建文件夹路径
                        file.createNewFile();   // 创建新文件

                        //  将二进制数据输出到文件中

                        InputStream ins = item.getInputStream();    // 上传的二进制数据
                        OutputStream ous = new FileOutputStream(file);  // 写入创建的文件

                        try {
                            byte[] bytes = new byte[1024];
                            int n ;
                            while((n = ins.read(bytes)) != -1) {
                                ous.write(bytes, 0, n);
                            }
                        }finally {
                            ins.close();
                            ous.close();
                        }
                    }
                }
            }
        }catch(FileUploadException e) {
            e.printStackTrace();
        }
        response.getWriter().write("ok");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值