web客户端通过ajaxfileupload方式上传文件

 

fileUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

    <head>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

        <title>Insert title here</title>

        <script type="text/javascript" src="jQuery/jquery-1.9.1.min.js"></script>

        <script type="text/javascript" src="jQuery/ajaxfileupload.js"></script>

        <script type="text/javascript">

          function fileClick(){

            if (confirm("摄像文件录制完成,是否上传?(默认存放目录:C:\\OCXRecordFiles)"))  {

              $("#file").click();  

            }  else  { 

              return;                

            }; 

          }

          function ajaxFileUpload()

          {   

                alert("ajaxFileUpload()函数");

              $.ajaxFileUpload

              (

                  {

                      url:'fileUploadServlet',//用于文件上传的服务器端请求地址

                      secureuri:false,//一般设置为false

                      fileElementId:'file',//文件上传空间的id属性  <input type="file" id="file" name="file" />

                      dataType: 'json',//返回值类型 一般设置为json

                      data: {//加入的文本参数   

                          "logoPath": "param1",   

                          "logoName": "param2"  

                      },                       

                      success: function (data, status)  //服务器成功响应处理函数

                      {

                            alert("ajax成功返回");

                          //alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量

                          if(typeof(data.error) != 'undefined')

                          {

                              if(data.error != '')

                              {

                                  //alert(data.error);

                              }else

                              {

                                  //alert(data.message);

                              }

                          }

                      },

                      error: function (data, status, e)//服务器响应失败处理函数

                      {

                          alert(e);

                      }

                  }

              );

              return true;

          }

          

          function openBrowse(){ 

            var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false; 

            if(ie){ 

              document.getElementById("file").click(); 

              document.getElementById("filename").value=document.getElementById("file").value;

            }else{

              var a=document.createEvent("MouseEvents");//FF的处理 

              a.initEvent("click", true, true);  

              document.getElementById("file").dispatchEvent(a); 

            } 

          } 

    </script>

    </head>

    <body>

      <input type="file" id="file"name="file" style="display:none" onchange="ajaxFileUpload()"/> 

      <input type="button" name="button" value="点我就像点击“浏览”按钮一样" onclick="javascript:openBrowse();" />

      <input type="text" id="filename"/> 

        <!-- 

        <input type="file" id="file" name="file"  onchange="ajaxFileUpload()" accept="audio/mp4, video/mp4, image/jpeg" style=""/>

        <input type="button" value="上传" onclick="fileClick()">               

         -->        

        <!-- 

        <style>

        #file{position:absolute;filter:alpha(opacity=0);opacity:0;size:1;width:50px}

        </style>

        

        <input type="file" id="file" name="file"  onchange="ajaxFileUpload()" accept="audio/mp4, video/mp4, image/jpeg" />

        <input type="button" value="上传" >           

         -->    

        <FORM METHOD=POST ACTION="fileUploadServlet" enctype="multipart/form-data">

        <A hideFocus class=addfileA id=aComposeAttach href="#">&nbsp;<INPUT hideFocus class=addfileI type=file size=1 name="FF" onchange="this.form.submit()"></A>

        <INPUT TYPE="submit" value="提交">

        </FORM>

        

    </body>

</html>
View Code

后台 FileUploadServlet.java

package com.zm.servlet;

import java.io.File;  

import java.io.IOException;  

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.FileUploadException;  

import org.apache.commons.fileupload.disk.DiskFileItemFactory;  

import org.apache.commons.fileupload.servlet.ServletFileUpload;  

  

/** 

 * Servlet implementation class FileUpload 

 */  

//@WebServlet("/FileUpload")  

public class FileUploadServlet extends HttpServlet {  

    private static final long serialVersionUID = 1L;  

         

    /** 

     * @see HttpServlet#HttpServlet() 

     */  

    public FileUploadServlet() {  

        super();  

        // TODO Auto-generated constructor stub  

    }  

  

    /** 

     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 

     */  

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  

        // TODO Auto-generated method stub  

        

        File tmpDir = new File("E:/Downloads/tmp/"); //临时存放目录 

        String saveDir = "E:/Downloads/upload/"; //最终存放目录

        

        // 检查是否有一个文件上传请求 

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);  

        if (!isMultipart) {  

            return;  

        }  

          

        // 创建一个基于硬件磁盘文件项的工厂  

        DiskFileItemFactory factory = new DiskFileItemFactory();  

          

        //指定在内存中缓存数据大小,单位为byte,这里设为1Mb

        factory.setSizeThreshold(1024); 

        //设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

        factory.setRepository(tmpDir);   

              



        ServletFileUpload upload = new ServletFileUpload(factory);  

          

        //setProgressListener  

        //upload.setProgressListener(new FileUploadProgressListener());  

          

        // Parse the request  

        List items = null;  

        try {  

            items = upload.parseRequest(request);  

        } catch (FileUploadException e1) {  

            // TODO Auto-generated catch block  

            e1.printStackTrace();  

        }  

          

        // Process the uploaded items  

        Iterator iter = items.iterator();  

        while (iter.hasNext()) {  

            FileItem item = (FileItem)iter.next();  

              

            //整个表单的所有域都会被解析,要先判断一下是普通表单域还是文件上传域  

            if (item.isFormField()) {  

                String name = item.getFieldName();  

                String value = item.getString();  

                System.out.println(name + ":" + value);  

            } else {  

                String fieldName = item.getFieldName();  

                String fileName = item.getName();  

                String contentType = item.getContentType();  

                boolean isInMem = item.isInMemory();  

                long sizeInBytes = item.getSize();  

                if(fileName.contains(":")){

                    String[] sArray = fileName.split("\\\\");

                    int iLength = sArray.length;

                    fileName = sArray[iLength -1];                    

                }

                System.out.println(fieldName + ":" + fileName);  

                System.out.println("类型:" + contentType);  

                System.out.println("是否在内在:" + isInMem);  

                System.out.println("文件大小" + sizeInBytes);  

                              

                File uploadedFile = new File(saveDir + fileName);  

                try {  

                    item.write(uploadedFile);  

                } catch (Exception e) {  

                    // TODO Auto-generated catch block  

                    e.printStackTrace();  

                }  

            }  

        }  

    }  

  

    /** 

     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 

     */  

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

        // TODO Auto-generated method stub  

        this.doGet(request, response);  

    }  

  

}  
View Code

web.xml

    <!-- 测试jquery fileUpload -->

    <servlet> 

    <servlet-name>fileUploadServlet</servlet-name>

    <servlet-class>com.zm.servlet.FileUploadServlet</servlet-class>

    </servlet>

    <servlet-mapping>

    <servlet-name>fileUploadServlet</servlet-name>

    <url-pattern>/fileUploadServlet</url-pattern>

    </servlet-mapping>

    
View Code

 

你可能感兴趣的:(ajaxFileUpload)