您的位置:首页 > 编程语言 > Java开发

java 实现 图片上传

2014-04-01 10:35 375 查看
        //存放上传图片的服务器地址

        List<String> imgList = null;

        if (ServletFileUpload.isMultipartContent(request)) {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            factory.setSizeThreshold(1024 * 512);

            ServletFileUpload fileUpload = new ServletFileUpload(factory);

            fileUpload.setFileSizeMax(10 * 1024 * 1024);

            String newName = null;

            List<FileItem> items = fileUpload.parseRequest(request);

            imgList = new ArrayList<String>();

            for (FileItem item : items) {

                if (!item.isFormField()) {

                    String image = null;

                    String name = item.getName();

                    String extName = name.substring(name.lastIndexOf("."));

                    newName = UUID.randomUUID().toString();

                    item.write(new File(request.getRealPath("/upload/" + newName + extName)));

                    image = "/upload/" + newName + extName;

                    imgList.add(image);

                }

            }

        }

 //jquery 实现上传图片并显示

 function PreviewImage(imgFile, showId) {

                var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/;

                var show = $(showId);

                var path;

                if (!pattern.test(imgFile.value))

                {

                    alert("仅支持jpg/jpeg/png/gif/bmp格式的照片!");

                    imgFile.focus();

                }

                else {

                    if (/msie/.test(navigator.userAgent.toLowerCase())) {

                        imgFile.select();

                        path = document.selection.createRange().text;

                        show.html = "";

                        show.css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")");

                    } else {

                        path = URL.createObjectURL(imgFile.files[0]);

                        show.html("<img src='" + path + "'/>");

                    }

                }

            }

   

    <input  type="file" name="front_image" class="upload" id="uoload_front" onchange='PreviewImage(this, "#front_image")'/>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: