我需要使用phonegaps Camera和File Transfer API将图像上传到网络服务。
例如,在Webservice上有:
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string SaveImage(string imageData, string filename)
{
string success = "Nothing";
try
{
string filename = "text.png";
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/devimg")))
{
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/devimg/"));
}
string path = HttpContext.Current.Server.MapPath("~/devimg/").ToString();
byte[] imgByte = Convert.FromBase64String(imageData);
using (var imgStream = new MemoryStream(imgByte, true))
{
Bitmap img = new Bitmap(imgStream);
Image i = (Image)img;
i.Save(path + "" + filename, ImageFormat.Png);
success = "Image created!!";
}
}
catch (Exception e)
{
success = e.ToString();
}
return success;
}
并在应用中有:
navigator.camera.getPicture( function( imgdata ){
//Base 64 encoded image file or whatever
}, CameraError , {
quality: 50,
destinationType: navigator.camera.DestinationType.DATA_URL,
sourceType: navigator.camera.PictureSourceType.CAMERA,
encodingType: navigator.camera.EncodingType.JPEG,
saveToPhotoAlbum: true
});
当前的web服务允许将Base 64编码的图像传递到它中,然后创建图像并使用给定的文件名保存它。但是,如果我尝试从phonegap应用程序访问web服务,它就无法工作。
我试图通过ajax访问webservice,但只是一堆错误。有没有更好的方法将图像上传到服务器?
答案 0 :(得分:2)
由于我无法选择评论作为答案,以下是我的代码以供将来参考: Phonegap JS:
navigator.camera.getPicture( function( imgdata ){
var urlimg = "http:// *URL ADDRESS* /mobile.asmx/SaveImage";
var params = new Object();
params.otherinfo = "Whaterver"
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imgdata.substr(imgdata.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
options.params = params;
options.chunkedMode = false;
var ft = new FileTransfer();
setTimeout(function() {
ft.upload(imgdata, urlimg, function(){
alert("Success")
}, function(err){
alert("Error: " + JSON.stringify(err));
}, options );
}, 600);
}, function(err){
alert(err);
} , {
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.CAMERA,
encodingType: navigator.camera.EncodingType.JPEG,
saveToPhotoAlbum: true
});
<强>的WebService 强>
[WebMethod]
public void SaveImage()
{
if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath("~/devimg"))){
System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/devimg/"));
}
string path = HttpContext.Current.Server.MapPath("~/devimg/").ToString();
var Request = HttpContext.Current.Request;
if (Request.Files.Count > 0){
var file = Request.Files[0];
file.SaveAs( path + file.FileName);
}
}
答案 1 :(得分:0)
见here。有关设置文件参数和调用Web服务的详细信息。