參考 http://blog.csdn.net/haozhoupan/article/details/49814631
首先聲明的是圖片我是上傳到服務器的Tomcat中郎笆,并保存路徑在數(shù)據(jù)庫中
第1步 安裝插件
1.1 安裝cordovaCamera
這個插件是用來拍照今瀑,或者說是打開手機上面的照相機功能的
DOS進入項目
Ionic plugin add cordova-plugin-camera
1.2 安裝cordovaFileTransfer
這個插件是上傳文件用的 ionic plugin add cordova-plugin-file-transfer
第2步.編寫頁面代碼
<div style="width:70px;height:70px;margin-left:auto;margin-right: auto;margin-top:5%;border-radius:5px;" ng-click="addPhoto();">

<img ng-if="user.image!=1" src={{user.image}} style="width:60px;height:60px;margin-left:-15%;margin-top:2%" >
</div>
其中: addPhoto()是鏈接JS中寫的圖片上傳方法
Img中的ng-if是判斷用戶是否修改了頭像懒震,若從沒修改過就給一個默認的頭像鳄厌,頭像修改過就顯示修改后的圖片
第3步JS代碼
3.1 在.controller中注入相關服務
$ionicActionSheet, $cordovaCamera, $cordovaFileTransfer
3.2 編寫下面JS代碼
// 添加圖片
$scope.addPhoto = function () {
$ionicActionSheet.show({
/* cancelOnStateChange: true,
cssClass: 'action_s',*/
titleText: "請選擇獲取圖片方式",
buttons: [{
text: '<b>拍照</b> 上傳'
}, {
text: '從 <b>相冊</b> 中選'
}],
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 = {
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,//Choose the format of the return value.
sourceType: Camera.PictureSourceType.CAMERA,//資源類型:CAMERA打開系統(tǒng)照相機;PHOTOLIBRARY打開系統(tǒng)圖庫
targetWidth: 150,//頭像寬度
targetHeight: 150//頭像高度
};
$cordovaCamera.getPicture(options)
.then(function (imageURI) {
//Success
$scope.imageSrc = imageURI;
//$scope.uploadPhoto();
var confirmPopup = $ionicPopup.confirm({
title: '<strong>提示</strong>',
template: '確認更新頭像?',
okText: '確認',
cancelText: '取消'
});
confirmPopup.then(function (res) {
$scope.uploadPhoto();//調(diào)用上傳功能
})
}, function (err) {
// Error
});
};
//選擇照片
$scope.pickImage = function () {
var options = {
maximumImagesCount: 1,
quality: 100,
destinationType: Camera.DestinationType.FILE_URI,//Choose the format of the return value.
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,//資源類型:CAMERA打開系統(tǒng)照相機拼缝;PHOTOLIBRARY打開系統(tǒng)圖庫
targetWidth: 150,//頭像寬度
targetHeight: 150//頭像高度
};
$cordovaCamera.getPicture(options)
.then(function (imageURI) {
//Success
$scope.imageSrc = imageURI;
// $scope.imageSrc= imageURI.substring(0,imageURI.lastIndexOf("?"));//獲取手機上的圖片可能后面出現(xiàn)娱局?時間戳
// $scope.uploadPhoto();
var confirmPopup = $ionicPopup.confirm({
title: '<strong>提示</strong>',
template: '確認更新頭像?',
okText: '確認',
cancelText: '取消'
});
confirmPopup.then(function (res) {
$scope.uploadPhoto();//調(diào)用上傳
})
}, function (err) {
// Error
});
};
$scope.uploadPhoto = function () {
// var requestParams = "?callback=JSON_CALLBACK";
var options = new FileUploadOptions();
var server = encodeURI('注意這寫的是你的后臺請求地址');
var fileURL = $scope.imageSrc;
alert("1 fileURL= "+fileURL);
var params = {
fileKey: "file",//相當于form表單項的name屬性
fileName: fileURL.substr(fileURL.lastIndexOf('/') + 1),
mimeType: "image/jpeg",
chunkedMode : true,
id:$scope.user.id
};
options.params = params;
//alert("2 options.fileKey = " +options.params.fileKey+" 3fileName= "+options.params.fileName);
$cordovaFileTransfer.upload(server, fileURL, options)
.then(function (result) {
// Success!
//alert("Code = " + result.responseCode + "Response = " + result.response+ "Sent = " + result.bytesSent);
alert("頭像更換成功!咧七!");
}, 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步 編寫后臺代碼
在此以springMVC中的controller作為后臺
@ResponseBody
@RequestMapping(value = "saveFile", method = { RequestMethod.GET, RequestMethod.POST })
public void saveFile(@RequestParam("file") MultipartFile[] mFiles,String fileName,String id) throws MalformedURLException {
String targetDirectory = "D:\\apache-tomcat-8.0.9\\webapps\\hy\\image"; //保存在服務器上的tomcat中路徑
System.err.println("filename= "+fileName+" 用戶id= "+id);//得到參數(shù)文件名和用戶id
if(mFiles.length==0|| mFiles==null){
return ;
}else{
if(fileName.contains("?")){
fileName = fileName.substring(0, fileName.indexOf("?"));
}
for(MultipartFile mFile : mFiles){
//String fileName = mFile.getOriginalFilename();//重名圖片的覆蓋問題
File targetFile = new File(targetDirectory, fileName);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
mFile.transferTo(targetFile);
UserCenterDTO user = new UserCenterDTO();
String path = targetFile.getPath();
user.setImage(fileName);
user.setUid(id);
int a= userService.updateImage(user);
} catch (IllegalStateException isEx) {
isEx.printStackTrace();
} catch (IOException ioEx) {
ioEx.printStackTrace();
}
}
}
}
但是這樣會報MultipartResolver錯誤衰齐,所以在上面代碼之上加上以下代碼:
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSize(10000000);
return resolver;
}
附上結(jié)果圖:
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png
Paste_Image.png