jquery uploadify和apache Fileupload实现异步上传文件示例

时间:2021-09-16 17:19:57

jQuery Uploadify + Apache Fileupload异步上传文件示例
1、可以限制上传文件大小和类型,理论上任何类型的文件都可以上传(自己根据api配置即可);
2、后台使用Apache commons-fileupload-1.3.1.jar作为上传工具包,本示例支持一次性多文件上传;
3、文件上传目录可以任意指定,请在web.xml中配置;
Uploadify api 详见http://www.uploadify.com/documentation/

FileUploadServlet

 

复制代码代码如下:


package com.xiaoxing.upload;

 

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * <h1>Apache Fileupload文件上传(2014-5-3)</h1>
 * <p>1、如果你对本示例感兴趣并想了解更多,欢迎加入Java私塾在线学习社区(329232140)</p>
 * <p>2、针对这个例子小修小改便可移植到你的实际项目中。</p>
 */
public class FileUploadServlet extends HttpServlet {

    private static final long serialVersionUID = 7579265950932321867L;

    // 设置文件默认上传目录(如果你没有在web.xml中配置的话)
    private String uploadDir = "c:/"; // 文件上传目录
    private String tempUploadDir = "c:/"; // 文件临时存放目录(会话销毁后由监听器自动删除)

    /*
     * (non-Javadoc)
     * @see javax.servlet.GenericServlet#init()
     * 如果在web.xml中配置了文件上传目录则优先使用,判断文件目录是否存在,不存在就创建。
     */
    @Override
    public void init() throws ServletException {
        // 获取本项目所在真实硬盘目录
        String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        path = path.substring(0, path.indexOf("WEB-INF"));
        // 判断目标是否存在,不存在就建立
        String uploadDir = path.concat(this.getInitParameter("uploadDir"));
        String tempUploadDir = path.concat(this.getInitParameter("tempUploadDir"));
        File f_uploadDir = new File(uploadDir);
        File f_tempUploadDir = new File(tempUploadDir);
        if (!f_uploadDir.exists()) {
            f_uploadDir.mkdirs();
        }
        if (!f_tempUploadDir.exists()) {
            f_tempUploadDir.mkdirs();
        }
        // 给变量赋值
        this.uploadDir = uploadDir;
        this.tempUploadDir = tempUploadDir;
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) 
     * 不接收get方式提交的数据,返回上传失败状态码。
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response);
        PrintWriter out = response.getWriter();
        out.print("{\"error\":\"-1\""); // 非法提交方式
    }

    /*
     * (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     * 上传文件请求都是通常POST提交
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.setResponse(response); // 设置响应类型,以便前端解析
        PrintWriter out = response.getWriter();
        String result = "";
        try {
            // 检查本次是否一个文件上传请求
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                DiskFileItemFactory factory = new DiskFileItemFactory(); // 创建一个工厂基于磁盘的文件项
                factory.setRepository(new File(tempUploadDir)); // 配置储存库(确保安全的临时位置时)
                ServletFileUpload upload = new ServletFileUpload(factory); // 创建一个新的文件上传处理程序
                upload.setSizeMax(1024 * 1024 * 100); // 设置总体要求尺寸限制(建议前后台分别设置,因为前后台用到了不同的插件)
                List<FileItem> items = upload.parseRequest(request); // 解析请求
                Iterator<FileItem> iter = items.iterator(); // 处理上传的项目
                while (iter.hasNext()) { //如果是一次性上传多个文件,那这里会分别去保存
                    FileItem item = iter.next();
                    if (!item.isFormField()) { // 过滤表单里的非文件类型字段
                        if (!"".equals(item.getName())) { // 过滤非文件类型的input
                            String s_name = item.getName(); // 获得原始文件名
                            int position = s_name.lastIndexOf(".");
                            String s_fileType = s_name.substring(position, s_name.length()); // 获得文件后缀
                            String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
                            String s = uploadDir.concat("/").concat(date).concat("/");
                            //这里按日期分目录保存文件
                            File sf = new File(s);
                            if (!sf.exists()) {
                                sf.mkdirs();
                            }
                            String s_filePath = s.concat(UUID.randomUUID().toString()).concat(s_fileType);
                            File path = new File(s_filePath);
                            item.write(path);
                            result += s_filePath.concat(",");
                        } else {
                            result = "";
                            break;
                        }
                    }
                }
            } else {
                result = "";
            }
            String s_resultJSON = this.jointJSON(result); // 拼接返回前端JSON
            out.print(s_resultJSON);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

    /**
     * 拼接JSON,将保存文件的文件名和日期目录返回给前端(前端可能需要这个路径完成其他表单操作,比如将文件路径存放到数据库)
     * @param result JSON格式的字符串
     * @return
     * @throws UnsupportedEncodingException
     */
    private String jointJSON (String result) throws UnsupportedEncodingException {
        String str = "";
        if(!"".equals(result)) {
            String rs[] = result.split(",");
            StringBuffer buffer = new StringBuffer("{\"rows\":[");
            for (int i = 0; i < rs.length; i++) {
                String s_tmpName = rs[i];
                s_tmpName = s_tmpName.substring(uploadDir.length(), s_tmpName.length());
                buffer.append("{\"name\":\"").append(s_tmpName).append("\"},");
            }
            str = buffer.toString();
            str = str.substring(0, str.length() - 1).concat("]}");
        } else {
            str = "{\"error\":\"-2\""; //上传失败
        }
        return str;
    }

    /**
     * 设置响应类型ContentType为"application/x-json"
     * @param response
     */
    private void setResponse(HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("cache-control", "no-cache");
    }

}

 

test_upload.html

 

复制代码代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery Uploadify + Apache Fileupload异步上传文件示例(2014-5-3)</title>
<link rel="stylesheet" type="text/css" href="/js/uploadify/uploadify.css">
<script src="/js/jquery-1.9.0.js"></script>
<script src="/js/uploadify/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
 $('#fileupload').uploadify({
     'method'   : 'post',
     'buttonText' : 'flash上传文件',
     'fileSizeLimit' : '1024KB',
     'fileTypeExts' : '*.gif; *.jpg; *.png',
  'swf'      : '/js/uploadify/uploadify.swf',
  'uploader' : '/upload', //这是上传图片的路径,也就是我在web.xml里配置的servlet
  'onUploadSuccess' : function(file, data, response) { //图片上传成功后返回数据在这里处理
      var ary = eval("(" + data + ")").rows;
      for(var i = 0; i < ary.length; i++) {
          $("#J_div").append("<img style="margin: 3px auto 0px; padding: 0px 3px; outline: none; line-height: 25.2px; font-size: 14px; background: rgb(242, 246, 251); width: 640px; clear: both; border-top: 1px solid rgb(0, 153, 204); border-right: 1px solid rgb(0, 153, 204); border-left: 1px solid rgb(0, 153, 204); border-image: initial; border-bottom: none; font-family: tahoma, arial, "Microsoft YaHei";"> 复制代码代码如下:

<?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" metadata-complete="true" version="3.0">
  <welcome-file-list>
   <welcome-file>test_upload.html</welcome-file>
  </welcome-file-list>

  <servlet>
    <description>专门用来处理上传操作的servlet</description>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.xiaoxing.upload.FileUploadServlet</servlet-class>
        <init-param>
         <description>文件存放的正式目录,可以自己配置</description>
         <param-name>uploadDir</param-name>
         <param-value>/upload/images/</param-value>
        </init-param>
        <init-param>
         <description>文件存放的临时目录,可以自己配置,里的文件由下面配置的监听器自动删除。</description>
         <param-name>tempUploadDir</param-name>
         <param-value>/upload/temp</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/upload</url-pattern>
    </servlet-mapping>

    <listener>
     <description>临时文件资源清理,工具包自带,不用我们来写</description>
     <listener-class>org.apache.commons.fileupload.servlet.FileCleanerCleanup</listener-class>
   </listener>

</web-app>