java使用commons-fileupload进行文件上传

java中使用文件上传时需要使用特定的类库,这里使用commons-files类库进行文件上传,在http://commons.apache.org/proper/commons-fileupload/上下载commons-io和commons-files类库

        DiskFileUpload upload = new DiskFileUpload();
        upload.setHeaderEncoding("UTF-8");
        List<FileItem> list;
        try {
            list = upload.parseRequest(request);
            //  遍历上传的文件
            for(FileItem item:list){
                // 判断文件类型 
                if(item.isFormField()){
                    String name = item.getName();
                    String value = item.getString("UTF-8");
                }
                else{
                    // 获取上传文件
                    File remoteFile = new File(new String(item.getName().getBytes(),"UTF-8"));
// 创建保存文件 File file1 = new File(request.getContextPath()+"/attachment",remoteFile.getName()); file1.getParentFile().mkdirs(); file1.createNewFile(); // 创建流进行操作 InputStream inputStream = item.getInputStream(); OutputStream outputStream = new FileOutputStream(file1); try { int len = 0; byte[] bt = new byte[1024]; while( (len = inputStream.read(bt)) > -1){ outputStream.write(bt,0,len); } } finally { // 关闭流 inputStream.close(); outputStream.close(); }

 

posted @ 2016-01-15 17:11  守、护  阅读(325)  评论(0编辑  收藏  举报