您的位置:首页 > 其它

跨平台移动开发phonegap/cordova 3.3全系列教程-图片上传

2014-02-07 11:11 661 查看
以asp.net为例,服务端使用HttpHandler

代码如下

<%@WebHandlerLanguage="C#"Class="uploadHandler"%>

usingSystem;

usingSystem.Web;

usingSystem.IO;

usingSystem.Data;

publicclass
uploadHandler: IHttpHandler

{

public voidProcessRequest (HttpContext context){

context.Response.ContentType = "text/plain";

context.Response.Charset = "utf-8";

HttpPostedFile file = context.Request.Files["fileAddPic"];

// fileAddPic为app端FileUploadOptions传入参数,此点非常重要

string fileName = file.FileName;

string folder =
"~/upLoad";

string uploadPath =
HttpContext.Current.Server.MapPath(folder+
"\\");

if (file != null)

{

file.SaveAs(uploadPath +fileName);

context.Response.Write("上傳OK");

}

else

{

context.Response.Write("上傳失敗");

}

}

public boolIsReusable {

get {

return false;

}

}

App端代码

var pictureSource;
//picture source

var destinationType;
// setsthe format of returned value

document.addEventListener("deviceready",onDeviceReady,false);

function onDeviceReady() {

pictureSource = navigator.camera.PictureSourceType;

destinationType = navigator.camera.DestinationType;

}

//拍照上傳,uploadPhoto为拍照成功后调用函数(拍照成功后立即上传至服务端)

function capturePhoto() {

navigator.camera.getPicture(uploadPhoto, onFail, {

quality: 100,

destinationType: destinationType.FILE_URI,

sourceType: Camera.PictureSourceType.CAMERA,

encodingType: Camera.EncodingType.JPEG,

popoverOptions: CameraPopoverOptions

});

}

//從相冊選擇

function getPhoto() {

navigator.camera.getPicture(uploadPhoto, onFail, {

quality: 100,

destinationType: navigator.camera.DestinationType.FILE_URI,

sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY

});

}

//上传失败回调函数:cancelled为取消动作,不抛出异常

functiononFail(message) {

if (message.indexOf('cancelled')< 0) {

alert('出錯了:'+message);

}

}

//上傳圖片

function uploadPhoto(imageURI) {

var options =
newFileUploadOptions();

//用于设置参数,服务端的Request字串

options.fileKey = "fileAddPic";

options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);

//如果是图片格式,就用image/jpeg,其他文件格式上官网查API

options.mimeType = "image/jpeg";

//这里的uri根据自己的需求设定,是一个接收上传图片的地址

varuri = encodeURI("http://192.168.0.131:88/uploadHandler.ashx");

options.chunkedMode = false;

var ft = newFileTransfer();

ft.upload(imageURI, uri, uploadOK, onFail, options);

}

//上传成功回调函数:msg.response为服务端返回的文本

function uploadOK(msg) {

var response = msg.response;

alert(response);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐