一次提交,多文件上传

private List<FileUploadBean> upload(HttpServletRequest request, HttpServletResponse response) {

        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        String srcName = Constants.BLANK;

        // 需要处理
        if (!multipartResolver.isMultipart(request)) {
            throw new AppException("999999", "图片上传失败");
        }

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();

        System.out.println(multiRequest.getMultiFileMap());

        String tmpPath = CcjoinPropVarUtils.getStringProp("img.upload.path");

        File parent = new File(tmpPath);

        if (!parent.exists()) {
            parent.mkdirs();
        }

        List<FileUploadBean> result = new ArrayList<FileUploadBean>();

        while (iter.hasNext()) {

    //注意这里是getFile方法是获取第一个文件,而getFiles方法才是获取多个文件
            List<MultipartFile> fileList = multiRequest.getFiles(iter.next());

            if (CheckUtils.isNull(fileList)) {
                continue;
            }

            for (MultipartFile file : fileList) {

                srcName = file.getOriginalFilename();

                String fileName = UUID.randomUUID() + FileUtils.getFileExt(srcName);

                File srcFile = new File(tmpPath + fileName);

                BufferedOutputStream stream = null;

                InputStream in = null;
                try {
                    in = file.getInputStream();
                    stream = new BufferedOutputStream(new FileOutputStream(srcFile));

                    byte[] b = new byte[2048];
                    int len = 0;
                    while ((len = in.read(b)) != -1) {
                        stream.write(b, 0, len);
                    }

                    FileUtils.flush(stream);
                    result.add(new FileUploadBean(srcName, tmpPath, fileName));

                } catch (Exception e) {
                    throw new AppException(e);
                } finally {
                    FileUtils.close(in);
                    FileUtils.close(stream);
                }
            }
        }

        return result;
    }

posted @ 2017-01-24 15:25  乌瑟尔  阅读(447)  评论(0编辑  收藏  举报