首页 > 学院 > 开发设计 > 正文

Cordova文件传输插件fileTransfer

2019-11-09 17:34:58
字体:
来源:转载
供稿:网友

http://blog.csdn.net/chenglinping/article/details/42008143

任务要求:

访问手机的目录,选择一个文件,并使用该插件将指定文件传输到远程主机的某个指定目录中。

html代码:

<!DOCTYPE html><!--    Licensed to the Apache Software Foundation (ASF) under one    or more contributor license agreements.  See the NOTICE file    distributed with this work for additional information    regarding copyright ownership.  The ASF licenses this file    to you under the Apache License, Version 2.0 (the    "License"); you may not use this file except in compliance    with the License.  You may obtain a copy of the License at    http://www.apache.org/licenses/LICENSE-2.0    Unless required by applicable law or agreed to in writing,    software distributed under the License is distributed on an    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY     KIND, either exPRess or implied.  See the License for the    specific language governing permissions and limitations    under the License.--><html>    <head>        <meta charset="utf-8" />        <meta name="format-detection" content="telephone=no" />        <meta name="msapplication-tap-highlight" content="no" />        <!-- WARNING: for iOS 7, remove the width=device-width and height=device-height attributes. See https://issues.apache.org/jira/browse/CB-4323 -->        <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" />        <link rel="stylesheet" type="text/CSS" href="css/index.css" />        <title>Hello World</title>    </head>    <body>        <div class="app">            <h1>Apache Cordova</h1>            <div id="deviceready" class="blink">                <p class="event listening">Connecting to Device</p>                <p class="event received">Device is Ready</p>            </div>        </div>        <script type="text/javascript" src="cordova.js"></script>        <script type="text/Javascript" src="js/index.js"></script>        <!-- 照相机  -->        <script type="text/javascript" src="js/camera.js"></script>        <input type="button" value="take pictures" onclick="snapPictures()" />        <img style="width:100px;height:100px;position:absolute;left:100px;top:50px;" id="myImage" />                <!-- 地理位置 -->        <script type="text/javascript" src="js/geolocation.js"></script>        <input type="button" value="location" onclick="getLocation()" />                <!-- 文件传输 -->        <script type="text/javascript" src="js/fileTransfer.js"></script>        <input type="button" value="fetchFile" onclick="fetchPictures()" />        <!-- <input type="button" value="fileTransfer" onclick="startTransfer()" /> -->            </body></html>

js代码:

/**选择图片库***/function fetchPictures(){navigator.camera.getPicture(fetchPictureSuccess, fetchPictureFail, { quality: 50,        destinationType: Camera.DestinationType.FILE_URI,//存储照片的数据/路径        sourceType : Camera.PictureSourceType.PHOTOLIBRARY  ,//打开系统的图片库        encodingType: Camera.EncodingType.JPEG,        mediaType:Camera.MediaType.PICTURE,        popoverOptions : CameraPopoverOptions,        saveToPhotoAlbum: true    });}function fetchPictureSuccess(imageURI) {var image = document.getElementById('myImage');image.src = imageURI;picUrl = imageURI;    /**文件上传start***/              var serverUri = encodeURI('http://192.168.1.101:8080/testTransfer/test.do');    function fileTransferSuccess(result) {    alert("success");    alert("Code = " + result.responseCode + "Response = " + result.response     + "Sent = " + result.bytesSent);    }    function fileTransferError(error) {    alert("fail");    alert("An error has occurred: Code = " + error.code + "upload error source " + error.source        + "upload error target " + error.target);    }        var fileUploadOptions = new FileUploadOptions();    fileUploadOptions.fileKey = "file";    fileUploadOptions.fileName = picUrl.substr(picUrl.lastIndexOf('/')+1);    fileUploadOptions.mimeType = "image/jpeg";//    fileUploadOptions.chunkedMode = false;        var fileTransfer = new FileTransfer();    alert("picUrl : "+picUrl + "******serverUri : " + serverUri);// fileTransfer.onprogress = function(progressEvent) {//    if (progressEvent.lengthComputable) {//      loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);//    } else {//      loadingStatus.increment();//    }// };fileTransfer.upload(picUrl, serverUri,fileTransferSuccess, fileTransferError, fileUploadOptions);        /**文件上传end***/        }function fetchPictureFail(message) {    alert('Failed because: ' + message);}server端JAVA:

package com.cn.server;import java.io.File;import java.io.IOException;import java.net.URLDecoder;import java.util.Iterator;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * Servlet implementation class Test */@WebServlet("/Test")public class Test extends HttpServlet {private static final long serialVersionUID = 1L;       /*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   System.out.println("Doing post....");   System.out.println(request.getRequestURI());   /**   * 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("D://androidApp图片//", 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);   }}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response);}}server端web.xml:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>testTransfer</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <servlet>    <servlet-name>Test</servlet-name>    <servlet-class>com.cn.server.Test</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>Test</servlet-name>    <url-pattern>/test.do</url-pattern>  </servlet-mapping></web-app>

问题是:

cordova run Android之后发现一直上传失败报错:3 = FileTransferError.CONNECTION_ERR,修改一天多始终没发现js或者server代码出问题

最后我抱着死马当活马医,用别人的电脑访问我的server的URL,竟然过时连接失败,原来是我电脑自身的防火墙设置没有允许别人访问,修改如下:

在电脑的“控制面板/系统和安全/Windows 防火墙/自定义设置‘里关闭防火墙,就OK了。

太浪费时间了!!!


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表