AngularJS上传图片

只是我的方法,仅供参考

html部分

<a class="btn btn-default" ng-click="openDialog()">上传图片</a>
<a class="btn btn-primary" ng-click="save()" ng-disabled="project_form.$invalid || fullNum>0 || shortNum>0">
    保存
</a>
                    
<p>图片预览,点击预览图片可移除该图片</p>
<!--图片预览-->
<div ng-repeat="image in imageObj" ng-click="imgDel($index)">
    <img class="project-image" ng-src="{{image.base64}}"/>
</div>
<input type="file" id="fileInput" accept="image/*" file-model="images"
       onchange="angular.element(this).scope().imgUpload(this.files)" style="display:none"/>

js部分

$scope.query=function () {
    projectBuildingService.getProjectInfo($scope.projectId).then(function (data) {
        if(data && data.statusCode===200){
            $scope.projectInfo=data.result;
            if($scope.projectInfo.region) $scope.divisionName=$scope.projectInfo.region;
            else if($scope.projectInfo.city) $scope.divisionName=$scope.projectInfo.city;
            else if($scope.projectInfo.province) $scope.divisionName=$scope.projectInfo.province;
            if($scope.projectInfo.projectAttachmentList){
                $scope.imageList = $scope.projectInfo.projectAttachmentList;
                for(var i=0;i<$scope.imageList.length;i++){
                    var guid = (new Date()).valueOf()+i;   //通过时间戳创建一个随机数,作为键名使用
                    $scope.imageObj[guid]={
                        base64:$scope.imageList[i].attachmentPath,
                        imageId:$scope.imageList[i].imageId
                    };
                }
            }
        } else {
            tipService.popup.error(data.message);
        }
    }, function (error) {
        tipService.popup.error(error.message);
    });
};


//页面初始化
if($scope.state=="update") $scope.query();        


//弹出上传文件窗口
$scope.openDialog=function () {
    document.getElementById("fileInput").click();
};

$scope.reader=new FileReader();   //创建一个FileReader接口

//预览图片对象(待上传)
$scope.imageObj={};

//要删除的图片id数组
$scope.deleteReady=[];

//单次提交图片的函数(预览待上传的图片)
$scope.imgUpload = function(files) {
    var guid = (new Date()).valueOf();   //通过时间戳创建一个随机数,作为键名使用
    //FileReader的方法,把图片转成base64
    $scope.reader.readAsDataURL(files[0]);
    $scope.reader.onload = function(ev) {
        $scope.$apply(function(){
            $scope.imageObj[guid]={
                base64:ev.target.result  //接收base64
            };
        });
    };
};

//删除预览(待上传)的图片
$scope.imgDel = function(index) {
    var guidArr = [];
    for(var p in $scope.imageObj){
        guidArr.push(p);
    }
    if($scope.imageObj[guidArr[index]].imageId!=null) $scope.deleteReady.push($scope.imageObj[guidArr[index]].imageId);
    delete $scope.imageObj[guidArr[index]];
};

//向后台提交数据,上传图片。新增成功或编辑成功之后都会进入此方法
$scope.submitImageList = function(){
    var base64=null;
    var imageId=null;
    for(var guid in $scope.imageObj) {
        imageId=$scope.imageObj[guid].imageId;
        base64=$scope.imageObj[guid].base64;

        if(imageId==null){
            var data = new FormData();
            data.append('base64', base64);
            data.append('guid',guid);
            $http({
                method: 'post',
                url: '/api/project/attachment/add?projectCode='+projectBuildingService.shortCode,
                data:data,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            })
        }
    }

    //有计划删除的图片
    if($scope.deleteReady.length>0){
        var deleteReadyArr=angular.toJson($scope.deleteReady);
        var fd=new FormData();
        fd.append("deleteReadyArr",deleteReadyArr);
    }
    $http({
        method: 'post',
        url: '/api/project/attachment/delete',
        data:fd,
        headers: {'Content-Type': undefined},
        transformRequest: angular.identity
    })
};

后台controller部分:

/**
 * 更新项目附件
 */
@POST
@Path("/attachment/add")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "修改项目附件", notes = "修改项目附件", response = Response.class, httpMethod = "POST")
@ApiResponses(value = {})
public Response updateAttachment(@FormDataParam("guid") String guid,
                                 @FormDataParam("base64") String base64,
                                 @QueryParam("projectCode") String projectCode,
                                 @Context HttpServletRequest request) throws Exception {
    try {
        return ok(projectBusiness.addAttachment(guid,base64,projectCode,TokenUtil.getUserID(request)));
    } catch (Exception e) {
        return ResponseHelper.forbidden(e.getMessage());
    }
}

/**
 * 删除项目附件
 */
@POST
@Path("/attachment/delete")
@Produces(APPLICATION_JSON)
@ApiOperation(value = "删除项目附件", notes = "删除项目附件", response = Response.class, httpMethod = "POST")
@ApiResponses(value = {})
public Response deleteAttachment(@FormDataParam("deleteReadyArr") String deleteReadyArr) throws Exception {
    try {
        Integer[] deleteArr=(Integer[])JSONArray.toArray(JSONArray.fromObject(deleteReadyArr),Integer.class);
        return ok(projectBusiness.deleteAttachment(deleteArr));
    } catch (Exception e) {
        return ResponseHelper.forbidden(e.getMessage());
    }
}

posted on 2017-11-30 11:10  Yoooshiki  阅读(198)  评论(0编辑  收藏  举报

导航