国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

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了。

太浪費時間了!!!


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 全州县| 芮城县| 嘉黎县| 安徽省| 金湖县| 于都县| 大荔县| 麻江县| 偏关县| 房山区| 巴彦淖尔市| 梓潼县| 额尔古纳市| 中阳县| 岢岚县| 延川县| 康定县| 林芝县| 太康县| 白山市| 宜兰县| 清丰县| 西吉县| 金寨县| 沾益县| 兰坪| 孝义市| 固阳县| 河曲县| 麻栗坡县| 安西县| 大安市| 积石山| 洛宁县| 辽阳市| 蒙城县| 顺昌县| 庆元县| 隆化县| 宁武县| 界首市|