将图像从phonegap应用程序上传到服务器(servlet)

时间:2013-08-17 08:44:15

标签: android servlets cordova

如何使用servlet将Phonegap应用的图片上传到服务器?

我的功能如下:

function uploadPhoto(imageURI) {
            var options = new FileUploadOptions();
            options.fileKey="file";
            options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
            options.mimeType="image/jpeg";

            var params = new Object();
            params.value1 = "test";
            params.value2 = "param";

            options.params = params;
            options.chunkedMode = true;

            var ft = new FileTransfer();
            ft.upload(imageURI, "http://131.246.37.167**/upload**", win, fail, options);

我的servlet是这样的:

公共类FileUploadHandler扩展HttpServlet {     private final String UPLOAD_DIRECTORY =“C:/ uploads”;

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //process only if its multipart content
    if(ServletFileUpload.isMultipartContent(request)){
        try {
            List<FileItem> multiparts = new ServletFileUpload(
                                     new DiskFileItemFactory()).parseRequest(request);

            for(FileItem item : multiparts){
                if(!item.isFormField()){
                    String name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }

           //File uploaded successfully
           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }          

    }else{
        request.setAttribute("message",
                             "Sorry this Servlet only handles file upload request");
    }

    request.getRequestDispatcher("/result.jsp").forward(request, response);

}

}

Der web.xml(Tomcat eclipse)。

.... 

 <servlet>
            <servlet-name>FileUploadHandler</servlet-name>
            <servlet-class>FileUploadHandler</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>FileUploadHandler</servlet-name>
            <url-pattern>**/upload**</url-pattern>
        </servlet-mapping>
....

请有人有个主意吗?

迈克尔

1 个答案:

答案 0 :(得分:0)

可能您错过了添加服务器端口号和IP地址。

ft.upload(imageURI, "http://131.246.37.167:8080/**/upload**", win, fail, options);