移动端
function photo(){
api.getPicture({
sourceType : 'camera',//相机
//sourceType : 'album',//相册
encodingType : 'jpg',
mediaValue : 'pic',//图片
//destinationType : 'base64',//指定返回数据为base64编码后内容
destinationType : 'url', //指定返回数据为选取的图片地址
allowEdit : false,
quality : 100,
saveToPhotoAlbum : false
}, function(ret, err){
if(ret){
// alert(JSON.stringify(ret));
saveImg(ret.data);
}else{
alert(JSON.stringify(err));
}
});
}
//保存剪辑图像
function saveImg(path) {
api.showProgress({
title: '上传中...',
text: '请稍后...',
});
//alert(path);
//上传剪辑后的图像到服务器
api.ajax({
// report : false,
url : 'http://192.168.0.4:8880/examinesLog/uploadImg',
method : 'post',
dataType:'text',
data: {
stream: path //以二进制流的方式提交文件。stream为文件路径 可直接使用其他端API返回的结果,如api.getPicture回调的ret.data等
// files: {
// file: path
// }
}
}, function(ret, err) {
//alert(JSON.stringify(ret));
api.hideProgress();//关闭
if (ret == 1) {
api.toast({
msg : '上传成功'
});
}else{
api.toast({
msg : '上传错误',
duration : 3000,
location : 'bottom'
});
}
});
};
后台
/**
* 接收手持机上传图片
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping("/uploadImg")
@ResponseBody
public int uploadImg(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("图片上传开始...");
String destDir = "/upload/image";
//C:\Users\Administrator\AppData\Local\\Temp\\tomcat-docbase.6975319770322585211.8880\\upload\image\20200314
ServletInputStream inputStream = request.getInputStream();
//获取文件上传的真实路径
String uploadPath = request.getSession().getServletContext().getRealPath("/");
//System.out.println("真实路径->"+uploadPath);//C:\Users\Administrator\AppData\Local\Temp\tomcat-docbase.1442950471882905655.8880\
//保存文件的路径
String filepath = destDir + File.separator + createNewDir();//项目路径
//System.out.println("保存文件的路径->"+filepath);
File destfile = new File(uploadPath + filepath);
if (!destfile.exists()) {
destfile.mkdirs();
}
//文件新名称
String fileNameNew = getFileNameNew() + ".png";
File f = new File(destfile.getAbsoluteFile() + File.separator + fileNameNew);
if (!f.exists()) {
OutputStream os = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(os);
byte[] buf = new byte[1024];
int length;
length = inputStream.read(buf, 0, buf.length);
while (length != -1) {
bos.write(buf, 0, length);
length = inputStream.read(buf);
}
bos.close();
os.close();
inputStream.close();
String lastpath = filepath + File.separator + fileNameNew;
//System.out.println("返回图片路径:" + lastpath);
//return lastpath;
return 1;
}
return 0;
}
/**
* 为文件重新命名,命名规则为当前系统时间毫秒数
*
* @return string
*/
private static String getFileNameNew() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return fmt.format(new Date());
}
/**
* 以当前日期为名,创建新文件夹
*
* @return
*/
private static String createNewDir() {
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
return fmt.format(new Date());
}