以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);
}
针对程序员的养生保健微信18136761128(专治颈椎、久坐导到慢性疾病,已经上央视了,假一罚十)