ionic 图片上传Demo

ionic 图片上传Demo

1步 安装插件

1.1安装cordovaCamera

说明:这个插件是用来拍照,或者说是打开手机上面的照相机功能的

操作:打开DOS,进入ionic项目所在的目录,

输入命令:cordova plugin add cordova-plugin-camera,等待安装完毕后,去plugins目录下查看如果有cordova-plugin-camera这个文件夹,表示安装成功。

PS还可以输入以下两个命令进行安装,不过这是老版本的安装方法

1.cordova plugin add org.apache.cordova.camera

2.cordova plugin add https://github.com/apache/cordova-plugin-camera.git

 

1.2安装cordovaFileTransfer

说明:这个插件是用来上传文件使用的

操作:打开DOS,进入ionic项目所在的目录,

输入命令:cordova plugin add cordova-plugin-file-transfer,等待安装完毕后,去plugins目录下查看如果有cordova-plugin-file-transfer这个文件夹,表示安装成功

2步 编写页面

<div class="list">
    <div class="item">
        <div class="buttons">
            <button class="button button-small button-balanced" ng-click="addPhoto();">添加</button>
            <button class="button button-small button-balanced"  ng-click="uploadPhoto();">上传</button>
        </div>
    </div>
    
    <div class="item" ng-show="imageSrc != undefined">
        <img ng-src="{{imageSrc}}" class="full-image" style="width:150px;height:150px;"/>
    </div>
</div>

 

3步 编写JS

3.1controller中注入相关服务

$ionicActionSheet

$cordovaCamera

$cordovaFileTransfer

3.2编写下面JS

// 添加图片
$scope.addPhoto = function () {
    $ionicActionSheet.show({
        cancelOnStateChange: true,
        cssClass'action_s',
        titleText"请选择获取图片方式",
        buttons[
            {text'相机'},
            {text'图库'}
        ],
        cancelText'取消',
        cancel: function () {
            return true;
        },
        buttonClicked: function (index) {

            switch (index) {
                case 0:
                    $scope.takePhoto();
                    break;
                case 1:
                    $scope.pickImage();
                    break;
                default:
                    break;
            }
            return true;
        }
    });
};

//拍照
$scope.takePhoto = function () {
    var options {
        quality100,
        destinationTypeCamera.DestinationType.FILE_URI,//Choose the format of the return value.
        sourceTypeCamera.PictureSourceType.CAMERA,//资源类型:CAMERA打开系统照相机;PHOTOLIBRARY打开系统图库
        targetWidth150,//头像宽度
        targetHeight150//头像高度

    };

    $cordovaCamera.getPicture(options)
        .then(function (imageURI) {
            //Success
            $scope.imageSrc imageURI;
            $scope.uploadPhoto();
        }, function (err) {
            // Error
        });
};
//选择照片
$scope.pickImage = function () {
    var options {
        quality100,
        destinationTypeCamera.DestinationType.FILE_URI,//Choose the format of the return value.
        sourceTypeCamera.PictureSourceType.SAVEDPHOTOALBUM,//资源类型:CAMERA打开系统照相机;PHOTOLIBRARY打开系统图库
        targetWidth150,//头像宽度
        targetHeight150//头像高度
    };

    $cordovaCamera.getPicture(options)
        .then(function (imageURI) {
            //Success
            $scope.imageSrc imageURI;
            $scope.uploadPhoto();
        }, function (err) {
            // Error
        });
};


$scope.uploadPhoto = function () {
    var requestParams "?callback=JSON_CALLBACK";

    var server encodeURI('注意这写的是你的后台请求地址' requestParams);
    var fileURL $scope.imageSrc;
    var options {
        fileKey"file",//相当于form表单项的name属性
        fileNamefileURL.substr(fileURL.lastIndexOf('/'1),
        mimeType"image/jpeg"
    };

    $cordovaFileTransfer.upload(serverfileURLoptions)
        .then(function (result) {
            // Success!
            alert("Code = " result.responseCode "Response = " result.response"Sent = " result.bytesSent);
        }, function (err) {
            // Error
             alert("An error has occurred: Code = " error.code "upload error source " error.source "upload error target " error.target);
        }, function (progress) {
            // constant progress updates
        });

};

4步  编写后台代码

PS:在此以springMVC中的controller作为后台

 

 

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

 

String callback = request.getParameter("callback");

//获取图片项

MultipartFile multipartFile = multipartRequest.getFile("file");

//获取图片的相关信息

String fileName = multipartFile.getOriginalFilename();//文件名

if(fileName.contains("?")){

fileName = fileName.substring(0, fileName.indexOf("?"));

}

long fileSize = multipartFile.getSize();//文件大小

 

/*************上传图片到服务器start******************/

String uploadBasePath = request.getRealPath("/")+"upload-img\\original\\";

 

//上传路径

String uploadPath = uploadBasePath.concat(fileName);

 

//根据图片上传的最终路径,创建目录

DirectoryUtils.createDir(uploadPath);

          

//保存图片到服务器

File destFile = new File(uploadPath);

multipartFile.transferTo(destFile);

/*************上传图片到服务器end******************/

 

 

/*************向前台返回结果******************/

 

String  responseString  =JSONPUtil.toJSONPStr(“{\”state\”:\”success\”}”,callback);

out.print(responseString);

out.flush();

 

附上JSONPUtil类的代码:

/**

 * JSON格式的字符串转换成JSONP格式

 *

 */

public class JSONPUtil {

private static String responseString = "";

public static String toJSONPStr(String jsonStr , String callback){

if (callback != null && !callback.isEmpty()) {

    responseString = callback + "(" + jsonStr + ")";

else {

    responseString = jsonStr;

}

return responseString;

}

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值