如何使用Phonegap和JqueryMobile上传文件?

我正在使用JQM和PhoneGap为Android构建移动应用程序。 我需要将文件(图像)上传到远程服务器(来自galery或用相机拍照)。 基本上它可以使用phonegap文件AP​​I来完成,问题是服务器是为了支持简单的POST提交而编写的。

我需要的是在我的应用程序请求中“模拟”与从以下html表单发送的完全相同 。 另外我需要获得服务器响应。

我尝试使用phonegap文件AP​​I,但服务器端检索数据的结构与应有的不同。

我试图在我的应用程序中实现该表单,但“选择文件”按钮被禁用…

如何在不对服务器端进行任何更改的情况下实现?

您不能在Phonegap上使用输入文件。 它不受支持。 你需要做这样的事情:

  function onDeviceReady() { // Retrieve image file location from specified source navigator.camera.getPicture(uploadPhoto, function(message) { alert('get picture failed'); }, { quality: 50, destinationType: navigator.camera.DestinationType.FILE_URI, sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY } ); } function uploadPhoto(imageURI) { var options = new FileUploadOptions(); options.fileKey="file"; options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1)+'.png'; options.mimeType="text/plain"; var params = new Object(); options.params = params; var ft = new FileTransfer(); ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options); } function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); } function fail(error) { alert("An error has occurred: Code = " + error.code); console.log("upload error source " + error.source); console.log("upload error target " + error.target); } 

在getPicture方法中,您将选择您的文件源。 查看更多信息: http : //docs.phonegap.com/en/2.1.0/cordova_file_file.md.html#FileTransfer

编辑:

需要指定fileName扩展名以及以“text / plain”格式请求mimeType以文本格式发送图像。 对于params,如果你不需要它们,为什么要使用它们呢?

您不能在Phonegap上使用输入文件。 它不受支持。 你需要做这样的事情:

  
selectPicture
// Put own HTML format but call the fuction // Angular fuction $scope.selectPicture = function () { var srcType = Camera.PictureSourceType.SAVEDPHOTOALBUM; var options = { // Some common settings are 20, 50, and 100 quality: 50, destinationType: Camera.DestinationType.FILE_URI, // In this app, dynamically set the picture source, Camera or photo gallery sourceType: srcType, encodingType: Camera.EncodingType.JPEG, mediaType: Camera.MediaType.PICTURE, allowEdit: true, correctOrientation: true //Corrects Android orientation quirks } navigator.camera.getPicture(function cameraSuccess(imageUri) { MobileUploadFile(imageUri); }, function cameraError(error) { console.debug("Unable to obtain picture: " + error, "app"); }, options); } function MobileUploadFile(imageURI) { //console.log(imageURI); var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); options.mimeType="image/jpeg"; options.chunkedMode = false; var ft = new FileTransfer(); ft.upload(imageURI, encodeURI("http://www.example.com/upload.php"), function(result){ //console.log(JSON.stringify(result)); }, function(error){ //console.log(JSON.stringify(error)); }, options); }; // php file