【问题标题】:PhoneGap upload Image to server on form submitPhoneGap 在表单提交时将图像上传到服务器
【发布时间】:2014-04-28 19:14:17
【问题描述】:

我在这里遇到问题,因为一旦您选择图片,phonegap 图像就会上传到服务器。我不想在提交表单之前上传图像。图像会自动上传到服务器,这是我不想要的。我想用表单上传图像,其中表单包含更多需要与图像一起发送的字段。使用表单提交的可能方式有哪些?

<!DOCTYPE HTML >
<html>
<head>
<title>Registration Form</title>
<script type="text/javascript" charset="utf-8" src="phonegap-1.2.0.js"></script>
<script type="text/javascript" charset="utf-8">

    // Wait for PhoneGap to load
    document.addEventListener("deviceready", onDeviceReady, false);

    // PhoneGap is ready
    function onDeviceReady() {
// Do cool things here...
    }

    function getImage() {
        // 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);
        options.mimeType="image/jpeg";

        var params = new Object();
        params.value1 = "test";
        params.value2 = "param";

        options.params = params;
        options.chunkedMode = false;

        var ft = new FileTransfer();
        ft.upload(imageURI, "http://yourdomain.com/upload.php", win, fail, options);
    }

    function win(r) {
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
        alert(r.response);
    }

    function fail(error) {
        alert("An error has occurred: Code = " = error.code);
    }

    </script>
</head>
<body>
<form id="regform">
<button onclick="getImage();">select Avatar<button>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="text" id="workPlace" name="workPlace" class="" />
<input type="submit" id="btnSubmit" value="Submit" />
</form>
</body>
</html>

【问题讨论】:

    标签: image cordova upload


    【解决方案1】:

    创建两个可以分别调用的函数。一个用于获取图像的功能,另一个用于上传图像的功能。

    您可以执行以下操作。

    <!DOCTYPE html>
    <html>
      <head>
        <title>Submit form</title>
    
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8">
    
        var pictureSource;   // picture source
        var destinationType; // sets the format of returned value
    
        // Wait for device API libraries to load
        //
        document.addEventListener("deviceready",onDeviceReady,false);
    
        // device APIs are available
        //
        function onDeviceReady() {
            pictureSource = navigator.camera.PictureSourceType;
            destinationType = navigator.camera.DestinationType;
        }
    
    
        // Called when a photo is successfully retrieved
        //
        function onPhotoURISuccess(imageURI) {
    
            // Show the selected image
            var smallImage = document.getElementById('smallImage');
            smallImage.style.display = 'block';
            smallImage.src = imageURI;
        }
    
    
        // A button will call this function
        //
        function getPhoto(source) {
          // Retrieve image file location from specified source
          navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
            destinationType: destinationType.FILE_URI,
            sourceType: source });
        }
    
        function uploadPhoto() {
    
            //selected photo URI is in the src attribute (we set this on getPhoto)
            var imageURI = document.getElementById('smallImage').getAttribute("src");
            if (!imageURI) {
                alert('Please select an image first.');
                return;
            }
    
            //set upload options
            var options = new FileUploadOptions();
            options.fileKey = "file";
            options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType = "image/jpeg";
    
            options.params = {
                firstname: document.getElementById("firstname").value,
                lastname: document.getElementById("lastname").value,
                workplace: document.getElementById("workplace").value
            }
    
            var ft = new FileTransfer();
            ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
        }
    
        // Called if something bad happens.
        //
        function onFail(message) {
          console.log('Failed because: ' + message);
        }
    
        function win(r) {
            console.log("Code = " + r.responseCode);
            console.log("Response = " + r.response);
            //alert("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);
        }
    
        </script>
      </head>
      <body>
        <form id="regform">
            <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Select Photo:</button><br>
            <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    
            First Name: <input type="text" id="firstname" name="firstname"><br>
            Last Name: <input type="text" id="lastname" name="lastname"><br>
            Work Place: <input type="text" id="workplace" name="workPlace"><br>
            <input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
        </form>
      </body>
    </html>
    

    【讨论】:

    • 嗨!我正在使用您的代码,并且可以很好地拍摄图像并上传到服务器!但它不适用于显示图像,尽管它确实将路径分配给 image.src 但无法显示图像:(
    • 可能是我缺少一些插件吗?我已经在那里发布了完整的问题:stackoverflow.com/questions/28125080/…
    • 我在链接上查看了您的帖子。您修改后的代码正在尝试在 uploadPhoto 函数中显示图像,该函数在您上传照片之前不会被调用。将其放在示例中的 onPhotoURISuccess 之类的函数中。查看示例中的 getPhoto 函数。它是 navigator.camera.getPicture(YourFunctionNameHereThatDisplayTheImage, ...) 中的第一个参数
    • 我的uploadPhoto函数和你的onPhotoURISuccess一样,如果你看一下,它是第一个函数:)
    • 我不知道为什么,但我无法使用上面的代码选择图像,但如果我从正文中删除表单标签,图像会被检索。请帮忙?
    【解决方案2】:

    您已经在示例中发送自定义字段。

    var params = new Object();
    params.value1 = "test";
    params.value2 = "param";
    
    options.params = params;
    

    只需使用您的表单字段填充params

    【讨论】:

    • 如果表单字段为空怎么办..params 只是静态值。我想在表单提交时发送图像,但没有发生。
    • 在发送之前用您的表单内容填充参数...您是否使用 jQuery 之类的 params.name = $('#inputName').val() 等等..
    • 感谢您的建议,但选择头像按钮是表单中的第一个元素。您说的是填写字段,然后使用输入字段参数上传图像。我想在表单的提交按钮上上传图片。有什么建议吗?
    • @user3420072 您可以尝试使用表单中的“onSubmit”手动处理提交的内容和方式。您也可以尝试可疑的技巧:添加以形成不可见的输入,其值等于图像 base64 字符串
    • @Regent 值得注意的是,在某些设备(尤其是 ipad mini 和廉价的 android)上,使用来自 camera 的 base64 图像可能会导致内存错误。
    【解决方案3】:

    我也遇到了同样的问题,但我已经完成了一次单击使用两个服务器端调用。在此,首先调用提交数据并使用 JSON 在回调中获取其 id,然后使用此 id 上传图像。在服务器端使用此 ID 更新数据和图像。

    $('#btn_Submit').on('click',function(event) {
       event.preventDefault();
       if(event.handled !== true)
       {
          var ajax_call = serviceURL; 
          var str = $('#frm_id').serialize();                 
          $.ajax({
          type: "POST",
          url: ajax_call,
          data: str,
          dataType: "json",
          success: function(response){
                  //console.log(JSON.stringify(response))
            $.each(response, function(key, value) { 
                  if(value.Id){                               
                       if($('#vImage').attr('src')){
                             var imagefile = imageURI; 
                              $('#vImage').attr('src', imagefile);
                            /* Image Upload Start */
                              var ft = new FileTransfer();                     
                            var options = new FileUploadOptions();                      
                            options.fileKey="vImage";                      
                            options.fileName=imagefile.substr(imagefile.lastIndexOf('/')+1);
                            options.mimeType="image/jpeg";  
                            var params = new Object();
                            params.value1 = "test";
                            params.value2 = "param";                       
                            options.params = params;
                            options.chunkedMode = false;                       
                            ft.upload(imagefile, your_service_url+'&Id='+Id+'&mode=upload', win, fail, options); 
                          /* Image Upload End */
                       }      
                   }
    
                 }); 
              }
         }).done(function() {
              $.mobile.hidePageLoadingMsg();              
         })
    
       event.handled = true;
      }
      return false;
    });
    

    在服务器端使用 PHP

    if($_GET['type'] != "upload"){
      // Add insert logic code
    }else if($_GET['type'] == "upload"){
      // Add  logic for image 
      if(!empty($_FILES['vImage']) ){ 
        // Copy image code and update data  
      }
    }
    

    【讨论】:

      【解决方案4】:

      我无法让这些插件上传包含其他答案的文件。

      问题似乎源于FileTransfer plugin,其中指出:

      fileURL:表示设备上文件的文件系统 URL 或数据 URI。

      但这没有对我来说似乎正常工作。相反,我需要使用 File plugin 创建一个临时文件,使用数据 uri 为我获取一个 blob 对象:在他们的示例中,writeFile 是一个函数,它采用 fileEntry(由 createFile 返回)和 @ 987654326@(斑点)。写入文件后,可以检索其路径并将其传递给 FileTransfer 实例。看起来工作量很大,但至少现在正在上传。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-16
        相关资源
        最近更新 更多