Java Web使用Html5 FormData实现多文件上传

首先html页面定义有两种:

Html1

1

2

3

<form enctype="multipart/form-data" id="formfile">

<input type="file" name="file"/>

Html2

1

<input  type="file" multiple="multiple"  accept="image/gif, image/jpeg, image/png, image/jpg, image/bmp" />

 项目中我采用了Html2的方式

再看看上传的JS部分吧:

1

$(document).on("change", ".upload-img input:file", function() {

        var fileId = $(this).attr("id");
        var t_files = this.files;
        var imglength =  $("#view_" + fileId).parent().parent().find(".upload-img").length;

        if (imglength==1) {
            if (t_files.length > 5) {
                new Message().showMsg("最多选择五张图片");
                return false;
            } else if (t_files.length < 1) {
                new Message().showMsg("至少选择一张图片");
                return false;
            }
        }else if(t_files.length+imglength>6) {
            new Message().showMsg('最多再选择'+ (6-parseInt(imglength)) +'张图片');
            return false;
        }
        var data = new FormData();
        for (var i=0;i
'); $("#view_" + fileId).parent().nextAll().find('span').eq(0).text(parseInt($("#view_" + fileId).parent().nextAll().find('span').eq(0).text())+1); $("#view_" + fileId).parent().nextAll().find('span').eq(1).text(5-parseInt($("#view_" + fileId).parent().nextAll().find('span').eq(0).text())); }else{ $("#view_" + fileId).attr('src',imgUrl); $("#view_" + fileId).nextAll().find('input').hide(); $("#view_" + fileId).parent().nextAll().remove('p'); } } } }).fail(function (res) { //console.log("error") })

上面第19行代表初始化formdata对象,其有两种创建方法,对于使用html2来说使用该方式来创建,使用html1来说可以使用 var data = new FormData(document.getElementById("#formfile");两种创建方式基本没有区别;第22-23行是可以给formdata添加其他属性的,,按需选择,21行是添加文件必须要写的.ajax部分 32 33行是必须要设置的,网上有说明,我就不多说了;

Java代码部分:

public void multipleCommentImageUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false)List files) {
        response.setContentType("text/html;charset=utf-8");
        UserSession user = WebUtil.getSessionUser(request);
        for (MultipartFile file:files) {
            String fileName = file.getOriginalFilename(); //获取文件名
        }
        UploadMessage message = new UploadMessage();
        Map map1 = new HashMap();

        try {
            Map map = this.multipleUpload(request, files);
           };
protected Map multipleUpload(HttpServletRequest request, List files) throws IllegalStateException, IOException {

        Map map =new HashMap();
        for(MultipartFile file:files) {
            if (file == null) {
                map.put("status",-1);
                map.put("statusInfo","上传参数不能为空");
                return map;
            }
        }

        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Enumeration params = multiRequest.getParameterNames();
            String upDir = null;
        //获得formdata对象中自定义的一些属性,是枚举类型
            while (params.hasMoreElements()) {
                String name = (String)params.nextElement();
                upDir = multiRequest.getParameter("upDir");
            }
            //取得request中的所有文件名
            Iterator iter = multiRequest.getFileNames();
            List list = new ArrayList<>();
            MultiValueMap multiValueMap = multiRequest.getMultiFileMap();
            List fileList = multiValueMap.get("file");
            for (MultipartFile file:fileList){
             //这里上传多张图片
                StringBuffer url = new StringBuffer("");
                Map map1 = new HashMap<>();
                if (file != null) {
                    //取得当前上传文件的文件名称
                    String originalFilename = file.getOriginalFilename();
                    //如果名称不为“”,说明该文件存在,否则说明该文件不存在
                    if (originalFilename != null && originalFilename.trim() != "") {
                        String suffix = "";

                        if (originalFilename.indexOf(".") > -1) {
                            suffix = originalFilename.substring(originalFilename.lastIndexOf("."), originalFilename.length());
                        }

                        if (notImageFormat(suffix)) {
                            map.put("statusInfo",imageFomat);
                            return map;
                        }
                        if (isPassSize(file.getSize())) {
                            map.put("stateInfo",imageSize);
                            return map;
                        }
                        //重命名上传后的文件名
                        String fileName = idWorker.nextId() + suffix;
                        String dir = DateTimeUtil.formatDateTime("yy/MM/dd");

                        if (!StringUtils.isBlank(upDir)){
                            url.append("/").append( upDir);
                        }
                        url.append("/").append(dir).append("/");

                        //定义上传路径
                        String path = ParamUtil.imageServiceRealPath + url;
                        //上传图片
                        imageUploadService.uploadImage(path, fileName, file.getInputStream());
                        String allUrl = url + fileName;
                        map1.put("imagePath",url.toString());
                        map1.put("imageName",fileName);
                        map1.put("imageUrl",ParamUtil.imageServicePath + allUrl);
                        list.add(map1);
                    }
                }
            }
            map.put("status",0);
            map.put("statusInfo","success");
            map.put("imgs",list);
        }
        return map;
    }

 

 

 

https://www.cnblogs.com/kanyun/p/7159232.html

你可能感兴趣的:(JS)