一.页面edit.html
<!-- 图片上传指令引入-->
<load-img to-show="$parent.photosUrl"></load-img>
二. service.js
starter_services.directive('loadImg', function($cordovaCamera,$ionicActionSheet,$cordovaFileTransfer,$ionicPopup){
return {
restrict: 'EACM',
replace: true,
scope:{
toShow:'='
},
templateUrl: 'templates/template/directive/loadImg.html',
link: function (scope,elements,attrs) {
console.log(scope)
console.log(attrs)
scope.image = IMAGE;
//上传图片
if(scope.$parent.$parent.showPicList.length==0){
scope.recordList=[]; //接收图片路径的集合
}else{
scope.recordList=scope.$parent.$parent.showPicList;
}
scope.uploadImg = function () {
var hideSheet = $ionicActionSheet.show({
buttons: [
{text: '拍照'},
{text: '从手机相册选择'}
],
cancelText: '取消',
cancel: function () {
},
buttonClicked: function (index) {
if (index == '0') {
document.addEventListener("deviceready", function () {
//拍照
var options = {
//照片质量0-100
quality: 100,
//返回类型:DATA_URL= 0,返回作为 base64 编码字串。 FILE_URI=1,返回影像档的 URI。NATIVE_URI=2,返回图像本机URI (例如,资源库)
destinationType: Camera.DestinationType.DATA_URL,
//从哪里选择图片:PHOTOLIBRARY=0,相机拍照=1,SAVEDPHOTOALBUM=2。0和1其实都是本地图库
sourceType: Camera.PictureSourceType.CAMERA,
//是否允许编辑图片
allowEdit: false,
//保存的图片格式: JPEG = 0, PNG = 1
encodingType: Camera.EncodingType.JPEG,
//照片宽度
targetWidth: 500,
//照片高度(如果是在电脑上显示,宽高需要设大一点,不然小图扩充后会很虚)
targetHeight: 500,
//可选媒体类型:圖片=0,只允许选择图片將返回指定DestinationType的参数。 視頻格式=1,允许选择视频,最终返回 FILE_URI。ALLMEDIA= 2,允许所有媒体类型的选择。
mediaType: 0,
//使用前后摄像头类型:后0 前1
cameraDirection: 0,
popoverOptions: CameraPopoverOptions,
//拍照后是否存到相册
saveToPhotoAlbum: true,
//修改方向 设为true后可解决拍照后旋转90°的问题
correctOrientation: true
};
$cordovaCamera.getPicture(options).then(function (imageData) { //拍照成功后回调
scope.imageSrc = "data:image/jpeg;base64," + imageData;
scope.recordList.push(scope.imageSrc);
scope.$parent.$parent.showPicList = scope.recordList;
// if(scope.$parent.$parent.photoPath==""){
// scope.$parent.$parent.photoPath = imageData;//页面上的显示列表
// }else{
// scope.$parent.$parent.photoPath = scope.$parent.$parent.photoPath + ","+ imageData;//页面上的显示列表
// }
upImageService(scope.imageSrc);
}, function (err) {
// error
});
}, false);
} else if (index == '1') {
document.addEventListener("deviceready", function () {
//从手机相册选择
var options = {
destinationType: Camera.DestinationType.FILE_URI,
sourceType: 2, //设为0或2,调用的就是系统的图库
quality: 100,
allowEdit: false,
targetWidth: 500,
targetHeight: 500
};
$cordovaCamera.getPicture(options).then(function (imageURI) {
scope.imageSrc = imageURI;
scope.recordList.push(scope.imageSrc);
scope.$parent.$parent.showPicList = scope.recordList;
// if(scope.$parent.$parent.photoPath==""){
// scope.$parent.$parent.photoPath = imageURI;//页面上的显示列表
// }else{
// scope.$parent.$parent.photoPath = scope.$parent.$parent.photoPath + "," + scope.imageSrc;//页面上的显示列表
// }
upImageService(imageURI);
}, function (err) {
// error
});
}, false);
}
return true;
}
})
};
//图片本身上传至服务器
var remitPic = ""; //返回的图片路径
var upImageService = function (imageURI) {
document.addEventListener('deviceready', function () {
var url = URL + "/upload/uploadFile";
var imageUrl = imageURI;
var options = {};
$cordovaFileTransfer.upload(url, imageUrl, options)
.then(function (result) {
var imageFile = JSON.parse(result.response);
remitPic = imageFile.file;
scope.$parent.$parent.photosUrl = scope.recordList.join(',');//在原控制器里可接收到改编后的值
//updateimg(remitPic); //上传图片路径到数据库
}, function (err) {
}, function (progress) {
// constant progress updates
});
}, false);
};
//删除图片
scope.delete=function(index,img){
var confirmPopup = $ionicPopup.confirm({
title: '',
template: '是否确认删除',
});
confirmPopup.then(function(res) {
if(res) {
scope.recordList.splice(index, 1);
scope.$parent.$parent.photosUrl = scope.recordList.join(',');//数组直接转字符串,在原控制器里可接收到改编后的值
}
});
}
}
};
});
注:通过scope.$parent.$parent.photosUrl = scope.recordList.join(',');可在edit.html对应的控制器中,即edit.js中,直接取得$scope.photosUrl的值
三.java
/**
* @author a 文件上传控制器
*/
@Controller
@RequestMapping(value = "/upload")
public class UploadController {
@RequestMapping(value = "uploadFile", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public Map<String, Object> uploadFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
// ImageInfo imageinfo = new ImageInfo();
Map<String, Object> mp = new HashMap<String, Object>();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
//返回的图片名称集合
List<String> fileNameArray = new ArrayList<String>();
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 记录上传过程起始时的时间,用来计算上传时间
int pre = (int) System.currentTimeMillis();
// 取得上传文件
MultipartFile file = multiRequest.getFile(iter.next());
if (file != null) {
// 取得当前上传文件的文件名称
String myFileName = file.getOriginalFilename();
// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
if (myFileName.trim() != "") {
String fileTyps = myFileName.substring(myFileName.lastIndexOf("."));
// String tempName="demo"+fileTyps;
String tempName = UUID.randomUUID().toString() + fileTyps;
// 创建文件夹
String folderPath = ConstantValueUtils.getSaveVoicePath() + File.separator + folderName();
File fileFolder = new File(folderPath);
if (!fileFolder.exists() && !fileFolder.isDirectory()) {
fileFolder.mkdir();
}
File uploadFile = new File(folderPath + File.separator + tempName);
file.transferTo(uploadFile);
myFileName = folderName() + File.separator + tempName;
fileNameArray.add(myFileName);
// mp.put("file", myFileName);
// return mp;
}
}
// 记录上传该文件后的时间
int finaltime = (int) System.currentTimeMillis();
// 记录上传该文件后的时间
System.out.println(finaltime - pre);
}
}
mp.put("file", fileNameArray);
return mp;
}
/**
* 得年月日的文件夹名称
*
* @return
*/
public String getCurrentFilderName() throws Exception{
Calendar now = Calendar.getInstance();
return now.get(Calendar.YEAR) + "" + (now.get(Calendar.MONTH) + 1) + "" + now.get(Calendar.DAY_OF_MONTH);
}
/**
* 创建文件夹
*
* @param filderName
*/
public void createFilder(String filderName) throws Exception {
File file = new File(filderName);
// 如果文件夹不存在则创建
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
/**
* 文件扩展名
*
* @param fileName
* @return
*/
public String extFile(String fileName) throws Exception{
return fileName.substring(fileName.lastIndexOf("."));
}
/**
* 当前日期当文件夹名
*
* @return
*/
public String folderName() throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String str = sdf.format(new Date());
return str;
}
}
注:上传的路径,在springmvc.xml里配置,如下
<!-- 常量bean -->
<bean class="cn.hezheng.utils.ConstantValueUtils">
<property name="saveVoicePath" value="/websites/projects/images"></property>
</bean>