使用PhoneGap,ajax和web service.net将图像上传到远程服务器

时间:2013-03-19 14:33:56

标签: jquery .net ajax cordova

我想在Phonegap应用中捕获图像,然后使用$发送。 ajax方法使用Web服务将其发送到远程服务器。净。

我无法使用“upload”方法发送到服务器,因为它不接受uri .asmx 我需要一个方法$。 ajax的帖子。 我使用网络服务:

[WebMethod]
public bool SavePhoto(Guid IdPrestation, Guid IdPhoto, byte[] ImgIn)
{
    System.IO.MemoryStream ms = new System.IO.MemoryStream(ImgIn);
    System.Drawing.Bitmap b =(System.Drawing.Bitmap)System.Drawing.Image.FromStream(ms);
    //Si le repertoire n'existe pas alors on le crée
    //  if (! RepertoirePhotoExist(IdPrestation))
    //{
           System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("Photos/" + IdPrestation.ToString()));
    //}
    string strFichier = HttpContext.Current.Server.MapPath("Photos/" + IdPrestation.ToString() + "/" + IdPhoto.ToString() + ".jpg");
    // Si le fichier existe alors
    if (System.IO.File.Exists(strFichier))
    {
        System.IO.File.Delete(strFichier);
    }
    else
    {
        b.Save(strFichier, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
        return true;
}

1 个答案:

答案 0 :(得分:0)

您应该使用Phonegap提供的CameraFileUploadOptions个对象

您的代码看起来像这样

document.addEventListener("deviceready", function() {

    var cameraParams = { 
        quality : 20,
        destinationType: Camera.DestinationType.FILE_URI,
        correctOrientation: true
    };
    navigator.camera.getPicture(onPhotoTakenSuccess, function() {}, cameraParams);

    var onPhotoTakenSuccess = function(imageUri) {

        var url = "http://yourserviceurl/service.asmx/Upload";

        var params = new Object();
        params.otherinfo = "whatever";  //you can send additional info with the file

        var options = new FileUploadOptions();
        options.fileKey = "file";
        options.fileName = imageUri.substr(imageUri.lastIndexOf('/')+1);
        options.mimeType = "image/jpeg";
        options.params = params;
        options.chunkedMode = false;

        var ft = new FileTransfer();
        ft.upload(imageUri, url, successCallback, errorCallback, options);
    };


}, false);

您的网络服务方法应如下所示:

[WebMethod]
public void Upload()
{
    var file = Request.Files[0];
    string otherInfo = Request["otherinfo"];
    //do whatever you want to do with the file now
}