【转】Cordova文件传输插件fileTransfer
任务要求:
访问手机的目录,选择一个文件,并使用该插件将指定文件传输到远程主机的某个指定目录中。
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了。
太浪费时间了!!!
【转】Cordova文件传输插件fileTransfer的更多相关文章
- cordova文件传输系统插件使用:cordova-plugin-file-transfer
1. 添加插件:cordova plugin add cordova-plugin-file-transfer 2. 调用方法: var fileTransfer = new FileTransfer ...
- linux下常用文件传输命令 (转)
因为工作原因,需要经常在不同的服务器见进行文件传输,特别是大文件的传输,因此对linux下不同服务器间数据传输命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp,lftp, ...
- linux下常用文件传输命令(转)
因为工作原因,需要经常在不同的服务器见进行文件传输,特别是大文件的传输,因此对linux下不同服务器间数据传输命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp,lftp, ...
- Linux的文件传输命令总结
由于工作原因,须要常常在不同的server见进行文件传输,特别是大文件的传输,因此对linux下不同server间传输数据命令和工具进行了研究和总结.主要是rcp,scp,rsync,ftp,sftp ...
- Linux下几种文件传输命令
Linux下几种文件传输命令 sz rz sftp scp 最近在部署系统时接触了一些文件传输命令,分别做一下简单记录: 1.sftp Secure Ftp 是一个基于SSH安全协议的文件传输管理工具 ...
- cordova加载层、进度条、文件选择插件
在做cordova项目的时候,感觉应用的响应速度跟原生应用比相差甚远,一个主要问题就是如加载层.进度条等弹出对话框的效率不行.毕竟项目中的这些弹框都是用dom拼成的,dom的渲染效率和原生控件比起来慢 ...
- C#语言下使用gRPC、protobuf(Google Protocol Buffers)实现文件传输
初识gRPC还是一位做JAVA的同事在项目中用到了它,为了C#的客户端程序和java的服务器程序进行通信和数据交换,当时还是对方编译成C#,我直接调用. 后来,自己下来做了C#版本gRPC编写,搜了很 ...
- 在windows 与Linux间实现文件传输(C++&C实现)
要实现windows与linux间的文件传输,可以通过socket网络编程来实现. 这次要实现的功能与<Windows下通过socket进行字符串和文件传输>中实现的功能相同,即客户端首先 ...
- Windows下通过socket进行字符串和文件传输
今天在windows平台下,通过socket实现了简单的文件传输.通过实现这一功能,了解基本的windows网络编程和相关函数的使用方法. 在windows平台上进行网络编程,首先都需要调用函数WSA ...
随机推荐
- iOS开发多线程篇—创建线程
iOS开发多线程篇—创建线程 一.创建和启动线程简单说明 一个NSThread对象就代表一条线程 创建.启动线程 (1) NSThread *thread = [[NSThread alloc] in ...
- iOS开发UI篇—模仿ipad版QQ空间登录界面
iOS开发UI篇—模仿ipad版QQ空间登录界面 一.实现和步骤 1.一般ipad项目在命名的时候可以加一个HD,标明为高清版 2.设置项目的文件结构,分为home和login两个部分 3.登陆界面的 ...
- dll的编写和使用
备忘: 1-1: def方式创建:VC6找不到stdafx.h,所以创建空工程,stdafx 里面功能太高端,不用不影响.DLL工程建立好后,新建一CPP文件,叫dlltest.cpp,直接去copy ...
- Spring Bean配置
Spring 是什么 •Spring 为简化企业级应用开发而生. 使用 Spring 可以使简单的 JavaBean 实现以前只有 EJB 才能实现的功能. •Spring 是一个 IOC(DI) 和 ...
- vs git extensions简单使用方法
一.准备工具 0.下载Git windows版本下载 http://git-scm.com/download 1.下载Git Extensions.地址http://sourceforge.net/p ...
- 【转载】【Windows批处理IV】批量进行文件重命名
1.过滤文件名中所有数字.汉字.特殊字符(含空格) @echo off for %%a in (*.*) do ( if "%%~nxa" neq "%~nx0" ...
- 动手实现自己的 STL 容器《2》---- list
1. 序: 本文参考了侯捷的 <STL 源码分析>一书,出于兴趣,自行实现了简单的 list 容器. 学习了 STL 的 list 容器的源代码,确实能够提高写链表代码的能力.其中的 so ...
- Oracle帮助类
/// <summary> /// Copyright (C) Maticsoft /// 数据访问基础类(基于Oracle) /// 可以用户可以修改满足自己项目的需要. /// < ...
- poj 1363
这是一道数据结构的问题,用到了栈的知识.题目大意讲的是每一次有N辆车从A到B,但是要将车辆的顺序重新排列,可以通过中转站C来辅助排列,但是C符合先进后出的原则,这一点和栈的特性相同. 整个重新排序的过 ...
- 将Controller抛出的异常转到特定View
<!-- 将Controller抛出的异常转到特定View --> <bean class="org.springframework.web.servlet.handler ...