angularJs图片上传

1    功能需求
花几天时间做了一个上传四张图片的功能,一个字段对应一张图片,效果如图所示:
 angularJs图片上传
1.1    前台页面代码
1.1.1    Html

 angularJs图片上传
File控件:选择图片
Hidden:存储图片路径,传递给后台保存到数据库
createExteriorPicture1_preview层:预览图层
createExteriorPicture1_preview_large层:放大图片
1.1.2    Css
<style>
    .pic_div {
        display: none;
        position: relative;
    }

    .pic_clear {
        position: absolute;
        right: 115px;
        color: red;
    }

    /*图片放大遮罩层*/
    .mask {
        display: none;
    }

    .mask-box {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        z-index: 80;
        opacity: 0.5;
        background: #000;
    }

    .big-pic-wrap {
        position: fixed;
        top: 50%;
        left: 50%;
        margin-left: -300px;
        margin-top: -300px;
        width: 920px;
        height: 620px;
        padding: 10px;
        z-index: 90;
        background: #fff;
    }

    .bigPic {
        width: 900px;
        height: 600px;
    }

    /*关闭大图按钮*/
    .close-pic {
        position: absolute;
        top: -5px;
        right: -5px;
        display: inline-block;
        width: 24px;
        height: 24px;
        cursor: pointer;
        border-radius: 50% !important;
        background: #393A3C;
        text-align: center;
        line-height: 40px;
    }

    .close-pic:hover {
        background: #D43F27;
    }

    .close-pic > i {
        font-size: 25px;
        color: #fff;
    }
</style>
1.1.3    Js
// 读取图片
modelApp.service('fileReader', function ($q) {
    var onLoad = function (reader, deferred, scope) {
        return function () {
            scope.$apply(function () {
                deferred.resolve(reader.result);
            });
        };
    };
    var onError = function (reader, deferred, scope) {
        return function () {
            scope.$apply(function () {
                deferred.reject(reader.result);
            });
        };
    };

    var getReader = function (deferred, scope) {
        var reader = new FileReader();
        reader.onload = onLoad(reader, deferred, scope);
        reader.onerror = onError(reader, deferred, scope);
        return reader;
    }

    var readAsDataURL = function (file, scope) {/*上传图片的主函数*/
        var deferred = $q.defer();
        var reader = getReader(deferred, scope);
        reader.readAsDataURL(file);
        return deferred.promise;
    };

    return {
        readAsDataUrl: readAsDataURL
    };
});

var modelApp = angular.module("modelApp", ['ui.bootstrap', 'ui.select', 'ngFileUpload']);
modelApp.controller("modelController", function ($scope, $http, $location, $filter, Upload, fileReader) {
        //选择图片并上传至临时目录
        $scope.uploadImage = function (files, image, image_src, image_div) {
            if (files && files.length == 1) {
                Upload.upload({
                    url: '/bakmgr/control/uploadStoreExtionImage',
                    data: {file: files}
                }).then(function (resp) {
                    if (resp.data[0].status == 'success') {
                        $("#" + image).val(resp.data[0].urlPath);
                        $("#" + image_div).css("display", "block");
                        $("#" + image_src).attr("src", $("#" + image).val());
                    } else {
                        toastr.error(resp.data[0].message);
                    }
                }, function (resp) {
                    console.log('Error status: ' + resp.data[0].status);
                });
            }
        }

        // 清除图片
        $scope.clearImage = function (image_div, image) {
            $("#" + image_div).css("display", "none");
            $("#" + image).val("");
        }
// 预览图放大
        $scope.enlargePicture = function (div_large, img_src, img_large) {
            $("#" + div_large).css("display", "block");
            $("#" + img_large).attr("src", $("#" + img_src).val());
        }

        // 关闭放大图
        $scope.closeLargeImage = function (div_large) {
            $("#" + div_large).css("display", "none");
        }
    }
);
1.1.4    后台方法
public static String uploadStoreExtionImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Delegator delegator = (Delegator) request.getAttribute("delegator");
        try {
            String dirPath = EntityUtilProperties.getPropertyValue("general.properties",
                    "image.local.dirPath", delegator);// 定义本地磁盘路径
            String url = EntityUtilProperties.getPropertyValue("general.properties",
                    "image.virtualUrl", delegator);// 定义url访问路径
            JSONArray jsonArray = new JSONArray();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("UTF-8");
            List<FileItem> items = upload.parseRequest(request);
            net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
            String LocalPathFile = "";// 本地路径
            String urlPath = "";// 代表虚拟的全路径
            FileItem item = items.get(0);
            String filename = item.getName();
            if (filename == null || filename.trim().equals("")) {
                jsonObject.put("status", "error");
                jsonObject.put("message", "图片名称为空");
                jsonArray.add(jsonObject);
                PrintWriter pw = response.getWriter();
                pw.println(jsonArray.toString());
                pw.close();
                return null;
            } else if(item.getSize()>5*1024*1024) {
                jsonObject.put("status", "error");
                jsonObject.put("message", "图片大小不能超过5MB!");
                jsonArray.add(jsonObject);
                PrintWriter pw = response.getWriter();
                pw.println(jsonArray.toString());
                pw.close();
                return null;
            } else {
                InputStream in;
                in = item.getInputStream();
                // 准备时间文件夹并且时间格式 yyyy/MM/dd/HH
                String datePathDir = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
                // 准备时间毫秒数+三位随机数
                String millis = System.currentTimeMillis() + "";
                Random random = new Random();
                int randomNum = random.nextInt(999); //0-999的随机数
                String randomPath = millis + randomNum;
                // 创建文件夹
                //D:/noah-upload/yyyy/MM/dd
                String LocalPath = dirPath + datePathDir;
                File file = new File(LocalPath);
                if (!file.exists()) {
                    file.mkdirs(); //如果文件夹不存在则创建文件夹
                }
                // D:/noah-upload/yyyy/MM/dd/232323111ll.jpg
                LocalPathFile = LocalPath + "/" + randomPath + filename;
                FileOutputStream out = new FileOutputStream(LocalPathFile);
                byte buffer[] = new byte[1024];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                urlPath = url + datePathDir + "/" + randomPath + filename;
                in.close();
                out.close();
                item.delete();
                jsonObject.put("status", "success");
                jsonObject.put("urlPath", urlPath);
                jsonArray.add(jsonObject);
                PrintWriter pw = response.getWriter();
                pw.println(jsonArray.toString());
                pw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("门店信息上传图片出错");
        } finally {
            delegator.clearAllCaches();
        }
        return null;
    }
1.1.4.1    general.properties
image.local.dirPath = D:/noah-upload/
image.virtualUrl = http://localhost:8081/