|
本帖最后由 暗夜的忧伤 于 2015-4-9 11:07 编辑
首先需要require("$UI/system/lib/cordova/cordova");
1、js端
Model.prototype.buttonClick = function(event) {
var me = this;
function onSuccess(imageURI) {
me.uploadImage(imageURI);
}
function onFail(message) {
return message;
}
navigator.camera.getPicture(onSuccess, onFail, {
quality : 50,
sourceType : 1//0、2为从相册文件中选择,1为拍照
});
Model.prototype.uploadImage = function(imageURI) {
var deferred = when.defer();
var options = new FileUploadOptions();
options.fileKey = "fileAddPic";// 用于设置参数
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
// 如果是图片格式,就用image/jpeg,其他文件格式上官网查API
options.mimeType = "image/jpeg";
// 这里的uri根据自己的需求设定,是一个接收上传图片的地址
var uri = encodeURI("http://10.71.84.211:8080/news/uploadImage?userID=admin");
options.chunkedMode = false;
var params = new Object();
params.id = "1";
params.name = "test";
options.params = params;
var ft = new FileTransfer();
function success(result) {
deferred.resolve(imageURI);//改变执行状态
navigator.notification.progressStop();
// alert("成功" + JSON.stringify(result));
}
function fail(message) {
alert("失败:" + JSON.stringify(message));
}
// 上传回调
ft.onprogress = showUploadingProgress;
navigator.notification.progressStart("", "当前上传进度");
ft.upload(imageURI, uri, success, fail, options);
}
// 显示上传进度
function showUploadingProgress(progressEvt) {
if (progressEvt.lengthComputable) {
navigator.notification.progressValue(Math.round((progressEvt.loaded / progressEvt.total) * 100));
}
}
2、服务端
@POST
@Path("/uploadImage")
@Consumes("multipart/form-data")
public void upLoadImage(@Context HttpServletResponse response,
@Context HttpServletRequest request) throws IOException {
File file1 = null;
System.out.println("userID="+request.getParameter("userID"));
DiskFileUpload disFileUpload = new DiskFileUpload();
try {
List<FileItem> list = disFileUpload.parseRequest(request);
for (FileItem fileItem : list) {
if (fileItem.isFormField()) {
System.out.println(fileItem.getFieldName() + ":"
+ fileItem.getString());
} else {
if ("fileAddPic".equals(fileItem.getFieldName())) {
File remoteFile = new File(new String(fileItem
.getName().getBytes(), "UTF-8"));
System.out.println("开始遍历.....");
file1 = new File("C:/Users/HHYJ/Desktop/"//写入的位置,从相册中选择的图片没有后缀,需要自己处理下
+ fileItem.getName());
InputStream ins = fileItem.getInputStream();
OutputStream ous = new FileOutputStream(file1);
try {
byte[] buffer = new byte[1024];
int len = 0;
while ((len = ins.read(buffer)) > -1) {
ous.write(buffer, 0, len);
}
} finally {
ous.close();
ins.close();
}
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
when-master.zip
(148.82 KB, 下载次数: 7124)
|
评分
-
查看全部评分
|