JS部分:<pre name="code" class="javascript">function sc(obj) {
//调用上传成功 设置图片显示
ajaxPic(function(ret, err) {
$(obj).attr("src", sys_base_url + ret.filePath);
$("#imgs").val(ret.filePath);
//名字可传。。
}, "asdsadas")
}
function ajaxPic(callBack, fileName) {
api.actionSheet({
cancelTitle : '取消',
buttons : ['相机', '相册']
}, function(ret, err) {
if (ret.buttonIndex != 3) {
var _sourceType = ""
if (ret.buttonIndex == 1) {
_sourceType = 'camera';
} else {
_sourceType = 'library';
}
api.getPicture({
sourceType : _sourceType,
allowEdit : true,
quality : 100
}, function(ret, err) {
if (ret && ret.data) {
ajax('url', {
values : {
filename : fileName
},
files : {
file : ret.data
}
//如果上传成功走回调
}, callBack)
} else {
// alert('你没有选择图片')
api.toast({
msg : '你没有选择图片',
location : 'middle'
})
}
});
}
});
}
java部分:
public void up() {
// 获得磁盘文件条目工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 文件上传路径
String savePath = "/up/";
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上, 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tmp
* 格式的 然后再将其真正写到 对应目录的硬盘上
*/
factory.setRepository(new File(PathKit.getWebRootPath() + savePath
+ "/tmp"));
// 设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
String filePath = "";
String fileName = "";
String backFilePath = "";
factory.setSizeThreshold(1024 * 1024);
// 高水平的API文件上传处理
ServletFileUpload upload = new ServletFileUpload(factory);
// 提交上来的信息都在这个list里面
// 这意味着可以上传多个文件
// 请自行组织代码
List<FileItem> list = null;
FileItem item = null;
try {
this.getRequest().setCharacterEncoding("UTF-8");
list = upload.parseRequest(this.getRequest());
// System.out.println(list.size());
logger.info("{}", list.size());
for (int i = 0; i < list.size(); i++) {
item = list.get(i);
// 普通表单
if (item.isFormField()) {
// System.out.println(String.format("属性名:%s,值:%s",
// item.getFieldName(), item.getString()));
if (item.getFieldName().equals("fileName")) {
fileName = item.getString();
}
} else {
// System.out.println(String.format("属性名:%s,文件名:%s,文件大小:%s",
// item.getFieldName(), item.getName(), item.getSize()));
// 保存文件
if (item.getSize() > 0 && item.getName() != null) {
if (StrKit.isBlank(fileName)) {
filePath = savePath + System.currentTimeMillis()
+ "-" + item.getName();
} else {
filePath = savePath + fileName
+ item.getName().split("\\.")[1];
}
try {
item.write(new File(PathKit.getWebRootPath()
+ filePath));
backFilePath = filePath;
} catch (Exception e) {
e.printStackTrace();
}
}
logger.info("{}", item.getContentType());
if (item.getContentType().indexOf("image") != -1) {
try {
Thumbnails
.of(PathKit.getWebRootPath() + filePath)
.scale(0.25f)
.toFile(PathKit.getWebRootPath() + "/m"
+ filePath);
backFilePath = "/m" + filePath;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
if (StrKit.notBlank(backFilePath)) {
} else {
renderJson(new ReVo("上传失败"));
}
}