【问题标题】:Uploading issue with FileTransfer in PhoneGap在 PhoneGap 中上传 FileTransfer 的问题
【发布时间】:2018-01-08 21:22:05
【问题描述】:

我无法在 phone-gap android 版本中上传手机拍摄的图像。 对于 iOS,它工作正常,但相同的代码不适用于使用手机间隙的 android 版本

我收到 200 响应代码,但没有来自服务器的“成功”响应。

我使用的是cordova-1.7.0.js,目标SDK是Android 2.1。

这里是示例代码:

function imageUpload(imageURI)
{
    var options = new FileUploadOptions();
    options.fileKey="image";
    options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
    options.mimeType="image/jpeg";
    var params = new Object();
    var msg="test message";
    var token= "test token";
    params.message = msg;
    params.access_token = token;
    options.params = params;
    var ft = new FileTransfer();
    ft.upload(imageURI, "http://mydomain.info/demo/upload.php", win, fail, options,false);
}

【问题讨论】:

  • 你在“adb logcat”中看到了什么?服务器端的日志呢?
  • 我直接在设备上运行,所以我看不到任何关于服务器端的日志我有 Echo 我从我的设备发送的值,所以我可以看到该值,但什么也没有服务器,我只收到 200 个响应代码。
  • 06-08 17:13:56.834: D/FileTransfer(3812): 从服务器得到响应 06-08 17:13:56.834: D/FileTransfer(3812): Array()
  • options.chunkedMode = false;解决了我的问题。

标签: android cordova file-upload phonegap


【解决方案1】:

另外别忘了给安卓模拟器添加摄像头权限

HTML 代码:

<!DOCTYPE html>
<html>
    <head>
        <title>Login Page</title>
              <meta name="viewport" content="width=device-width, initial-scale=1">

     <script type="text/javascript" charset="utf-8" src="cordova-1.9.0.js"></script>
     <link rel="stylesheet"
href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
     <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script
src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>

    <script type="text/javascript">


        function PictureSourceType() {};
        PictureSourceType.PHOTO_LIBRARY = 0;
        PictureSourceType.CAMERA = 1;

        function getPicture(sourceType)
        {
             var options = { quality: 10 };
             if (sourceType != undefined) {
                  options["sourceType"] = sourceType;
                 // options["destinationType"] = destinationType.DATA_URL;
             }
             // if no sourceType specified, the default is CAMERA 
             navigator.camera.getPicture(getPicture_Success, null, options);
        };


        function getPicture_Success(imageData)
        {
                 alert("getpic success "+ imageData);
                document.getElementById("test_img").src =  imageData;
        };

        function success(response) {
            alert("Your photo has been uploaded!");
          };
          // callback if the photo fails to upload successfully.

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

        function uploadPhoto()
        {
            var imageFile = document.getElementById("test_img").src;
            alert(imageFile);




            var ft,options;


            options = new FileUploadOptions();
            options.fileKey = "profile_image";
              // name of the file:
              options.fileName = imageFile.substr(imageFile.lastIndexOf('/') + 1);
              // mime type:
              options.mimeType = "multipart/form-data";
              params = {
                val1: "some value",
                val2: "some other value"
              };
              options.params = params;



            ft = new FileTransfer();
            ft.upload(imageFile, 'http://10.0.2.2:8080/cio/uploadpic', success, fail, options);
            alert("There is something called file transfer " + imageFile);

        };

       </script>
        </head>

         <body>
     <div data-role="page" id="cameraPage">
    <div data-role="header" data-position="inline">
        <h1>Edit profile Pic</h1>
        <a href="index.html" data-icon="delete" class="ui-btn-right">Cancel</a>
    </div>

    <div data-role="content">
        <center>
        <img style="width: 60px; height: 60px" id="test_img" src="" />
        </center>

        <button onclick="getPicture()">From Camera</button>

        <button onclick="getPicture(PictureSourceType.PHOTO_LIBRARY)">From
            Photo Library</button>
        <button onclick="uploadPhoto()">Upload Photo</button>


    </div>

</div>

【讨论】:

    【解决方案2】:

    首先确保你的 doPost 方法被调用 如果未调用,请编写 doGet() 方法,并在该调用中按以下方式发布

    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request,response);
    } 
    

    然后,你需要将以下jar文件放在WEB-INF下的lib文件夹中

    1. commons-fileupload-1.2.2.jar
    2. commons-fileupload-1.2-javadoc.jar
    3. commons-fileupload-1.2-sources.jar
    4. commons-io-1.3.2.jar

    也将它们放在构建路径中。

    【讨论】:

      【解决方案3】:

      现在我们在 Cordova-1.9.0 上还添加了 apache 库:commons-io-2.4.JARS

      我一直在尝试将图片从 phonegap android 模拟器上传到 servlet 以存储图片

      Servlet 代码:uploadpic.java

      private static final String BASE_DIRECTORY = "/Users/tshah/Pictures";
      
      protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      
      //  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      
          System.out.println("Do post....");
      
          /**
          * The base upload directory. In this directory all uploaded files will
          * be stored. With the applet param tag 'directory' you can create a
          * subdirectory for a user. 
          * See http://www.javaatwork.com/parameters.html#directory for more 
          * information about the 'directory' param tag. For a Windows environment 
          * the BASE_DIRECTORY can be e.g. * 'c:/temp' for Linux environment '/tmp'.
          */
      
      
          boolean isMultipart = ServletFileUpload.isMultipartContent(request);
      
          // check if the http request is a multipart request
          // with other words check that the http request can have uploaded files
          if (isMultipart) {
      
            //  Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
      
            //  Create a new file upload handler
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);
      
            // Set upload parameters
            // See Apache Commons FileUpload for more information
            // http://jakarta.apache.org/commons/fileupload/using.html
            servletFileUpload.setSizeMax(-1);
      
            try {
      
              String directory = "";
      
              // Parse the request
              List items = servletFileUpload.parseRequest(request);
      
              // Process the uploaded items
              Iterator iter = items.iterator();
      
              while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
      
                // the param tag directory is sent as a request parameter to
                // the server
                // check if the upload directory is available
                if (item.isFormField()) {
      
                  String name = item.getFieldName();
      
                  if (name.equalsIgnoreCase("directory")) {
      
                    directory = item.getString();
                  }
      
                  // retrieve the files
                } else {
      
                  // the fileNames are urlencoded
                  String fileName = URLDecoder.decode(item.getName());
      
                  File file = new File(directory, fileName+".jpeg");
                  file = new File(BASE_DIRECTORY, file.getPath());
      
                  // retrieve the parent file for creating the directories
                  File parentFile = file.getParentFile();
      
                  if (parentFile != null) {
                    parentFile.mkdirs();
                  }
      
                  // writes the file to the filesystem
                  item.write(file);
                }
              }
      
            } catch (Exception e) {
              e.printStackTrace();
              response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
      
            response.setStatus(HttpServletResponse.SC_OK);
      
          } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
          }
      }
      

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题。我通过添加代码修复了它

        System.setProperty("http.keepAlive", "false");
        

        在 onCreate() 方法开头的主 java 文件中。 这个bug是apache cordova的unresolved bug

        【讨论】:

          【解决方案5】:

          在此处查看我的答案,这适用于我在 android 上(将图像和数据发送到 django rest api)以获取完整代码:

          android phonegap camera and image uploading

          我想诀窍在于:

          options.chunkedMode = true; //this is important to send both data and files
          

          也许还有这个:

          var url=encodeURI("http://your_url_for_the_post/");
          

          使用 url 编码的 url 传递给 FileTransfer

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-03-07
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-06-29
            • 1970-01-01
            • 2018-09-28
            相关资源
            最近更新 更多