Cordova文件传输插件fileTransfer

任务要求:

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

html代码:




   
       
       
       
       
       
       
        Hello World
   
   
       


           

Apache Cordova


           
       

       
       
       
       
       
       
        
       
       
       
        
       
       
       
       
        
   

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:




  testTransfer
 
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
 

 
    Test
    com.cn.server.Test
 

 
    Test
    /test.do
 

问题是:

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

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

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

太浪费时间了!!!

你可能感兴趣的:(js,个人笔记)