任务要求:

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

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>

  

JavaScript

/**选择图片库***/
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了。

太浪费时间了!!!

 
 
 
原文地址:http://blog.csdn.net/chenglinping/article/details/42008143
 

【转】Cordova文件传输插件fileTransfer的更多相关文章

  1. cordova文件传输系统插件使用:cordova-plugin-file-transfer

    1. 添加插件:cordova plugin add cordova-plugin-file-transfer 2. 调用方法: var fileTransfer = new FileTransfer ...

  2. linux下常用文件传输命令 (转)

    因为工作原因,需要经常在不同的服务器见进行文件传输,特别是大文件的传输,因此对linux下不同服务器间数据传输命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp,lftp, ...

  3. linux下常用文件传输命令(转)

    因为工作原因,需要经常在不同的服务器见进行文件传输,特别是大文件的传输,因此对linux下不同服务器间数据传输命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp,lftp, ...

  4. Linux的文件传输命令总结

    由于工作原因,须要常常在不同的server见进行文件传输,特别是大文件的传输,因此对linux下不同server间传输数据命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp ...

  5. Linux下几种文件传输命令

    Linux下几种文件传输命令 sz rz sftp scp 最近在部署系统时接触了一些文件传输命令,分别做一下简单记录: 1.sftp Secure Ftp 是一个基于SSH安全协议的文件传输管理工具 ...

  6. cordova加载层、进度条、文件选择插件

    在做cordova项目的时候,感觉应用的响应速度跟原生应用比相差甚远,一个主要问题就是如加载层.进度条等弹出对话框的效率不行.毕竟项目中的这些弹框都是用dom拼成的,dom的渲染效率和原生控件比起来慢 ...

  7. C#语言下使用gRPC、protobuf(Google Protocol Buffers)实现文件传输

    初识gRPC还是一位做JAVA的同事在项目中用到了它,为了C#的客户端程序和java的服务器程序进行通信和数据交换,当时还是对方编译成C#,我直接调用. 后来,自己下来做了C#版本gRPC编写,搜了很 ...

  8. 在windows 与Linux间实现文件传输(C++&C实现)

    要实现windows与linux间的文件传输,可以通过socket网络编程来实现. 这次要实现的功能与<Windows下通过socket进行字符串和文件传输>中实现的功能相同,即客户端首先 ...

  9. Windows下通过socket进行字符串和文件传输

    今天在windows平台下,通过socket实现了简单的文件传输.通过实现这一功能,了解基本的windows网络编程和相关函数的使用方法. 在windows平台上进行网络编程,首先都需要调用函数WSA ...

随机推荐

  1. gz

    不准备的话,是真的会滚粗的. leetcode  还是重新做起来叭. 那么就开始咯 8.22 leetcode 144 Binary Tree Preorder Traversal 二叉树的前序遍历 ...

  2. CodeForces #367 div2 D Trie

    题目链接:Vasiliy's Multiset 题意:这里有一个set容器,有三种操作,+ num, - num, ? num,分别代表往容器里加上num,或者拿走num,或着从容器里找一个数temp ...

  3. IEnumerable接口的Aggregate方法

    以前小猪为了累加一个集合中的类容通常会写出类似这样的C#代码: string result ="": foreach (var item in items) { result+=i ...

  4. iOS开发网络篇—监测网络状态

    iOS开发网络篇—监测网络状态 一.说明 在网络应用中,需要对用户设备的网络状态进行实时监控,有两个目的: (1)让用户了解自己的网络状态,防止一些误会(比如怪应用无能) (2)根据用户的网络状态进行 ...

  5. iptables基本规则

    注意:iptables只能被拥有超级权限的用户设置.   重启 清空 iptables 规则:在终端输入:   iptables -F iptables -X iptables -t nat -F i ...

  6. 实现用CSS切割图片的方法

    切割图片这里不是真正的切割,只是用CSS取图片中的一部分而已.这样做的好处就是减少了打开网页时请求图片的次数.主要有两种方式,一是做为某一元素的背景图片,二是用img元素的属性. 方法一: 用CSS中 ...

  7. SVG 2D入门11 - 动画

    交互性      SVG拥有良好的用户交互性,例如:1. SVG能响应大部分的DOM2事件.2. SVG能通过cursor良好的捕捉用户鼠标的移动.3. 用户可以很方便的通过设置svg元素的zoomA ...

  8. chrome49 新特性 chrome.org转载

    Transitioning from SPDY to HTTP/2 Thursday, February 11, 2016 Last year we announced our intent to e ...

  9. Modules

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  10. C语言基本数据类型

    一.数据类型与“模子” short.int.long.char.float.double 这六个关键字代表C 语言里的六种基本数据类型. 怎么去理解它们呢? 举个例子:见过藕煤球的那个东西吧?(没见过 ...