一、简介

  Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示;可以上传多个文件;

   详细的使用方法网上有很多,建议到官网参考,这里仅仅展示其使用的效果;

  官网:www.uploadify.com(注:本人今天就进入了一次官网,之后再也进不去了……);

  在官网下载最新的版本;但是本人下载Uploadify所需的所有JS最新文件,不知为何原因不能正确显示,只好将原有项目的JS文件拷贝进自己的项目中,其中必须的文件:jquery-1.4.2.min.js;

jquery.uploadify.v2.1.0.min.js;swfobject.js;uploadify.swf;

  其中swfobject.js这个JS是用于在HTML中方面插入Adobe Flash媒体资源(*.swf文件)的独立、敏捷的JavaScript模块,该模块中的JavaScript脚本能够自动检测PC、Mac机器上各种 主流浏览器对Flash插件的支持情况。

以上所需的JS文件本人全部在官网下载最新的版本,但是使用失败,我能力有限只能归罪于版本的兼容;便使用了原有的文件;


二、有了必须的资源之后,就是将所需的文件导入:

   下图便为项目的目录结构

205325511.jpg

项目准备好之后,便开始构建上传的功能了;当然要将需要的文件在jsp页面说明;

首先index.js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>更改头像</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0"> 
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
                                                                                                                                   
  <link rel="stylesheet" href="css/default.css" type="text/css"></link>
  <link rel="stylesheet" href="css/uploadify.css" type="text/css"></link>
  <link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css"></link>
                                                                                                                                 
  <script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
  <script type="text/javascript"     src="js/jquery.uploadify.v2.1.0.min.js"></script>
  <script type="text/javascript" src="js/swfobject.js"></script>
  <script type="text/javascript" src="js/fileupload.js"></script>
   //fileupload.js是自己封装的JS文件,主要便是使用uploadify插件
  </head>
  <body>
  <div> </div>
   <div style="font-size: 15px;">
   图片文件:&nbsp&nbsp&nbsp
  <input type="file" name="file" id="file" /></div>
  <input type="button" id="uploadFile" value="上传文件">
  <input type="button" id="cancelUpload" value="取消上传">
  <div id="fileList" style="height:51px;"></div>
</table>
  </body>
</html>

这个index.jsp的预览效果图如下:

205922754.jpg


这里使用uploadify插件的操作封装成JS文件也放在了js目录下(上面的截图中有被涂鸦了,嘿嘿),代码如下:

$(document).ready(function() {
            $("#file").uploadify({
                        'uploader' : 'js/uploadify.swf',
                        'script' : 'UploadServlet',
                        'cancelImg' : 'js/cancel.png',
                        'queueID' : 'fileList', // 和存放队列的DIV的id一致
                        'fileDataName' : 'file', // 和以下input的name属性一致
                        'auto' : false, // 是否自动开始
                        'multi' : false, // 是否支持多文件上传
                        'buttonText' : 'Brower', // 按钮上的文字
                        'simUploadLimit' : 1, // 一次同步上传的文件数目
                        'sizeLimit' : 3145728, // 设置单个文件大小限制 3MB
                        'queueSizeLimit' : 1, // 队列中同时存在的文件个数限制
                        'fileDesc' : '支持格式:jpg/jpeg', // 如果配置了以下的'fileExt'属性,那么这个属性是必须的
                        'fileExt' : '*.jpg;*.jpeg;',// 允许的格式
                        'displayData' : 'percentage',
                        onComplete : function() {
                            alert("文件上传成功");
                        },
                        onError : function(event, queueID, fileObj) {
                            alert("文件:" + fileObj.name + "上传失败");
                        }
                                                                                                                                               
                    });
            $("#uploadFile").click(function() {
                $("#file").uploadifyUpload();
                                                                                                                                   
            });
            });


到这里其前台的工作已经做完,便着手处理业务逻辑了;

三、当选择好文件之后,uploadify组件会如下显示一个进度条:

211358372.jpg

当你点击上传文件时候,便会调用你自己的文件上传的Servlet,实现文件的上传;先展示文件上传成功的界面:

211629339.jpg

下面为文件上传的Servlet:

package com.xzb.fileUpload;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("文件上传开始……");
        String savePath = generateDir();
        processUpload(request, response, savePath);
                                                                                            
    }
    /*
     * 上传处理方法
     */
    public void processUpload(HttpServletRequest request,
            HttpServletResponse response, String savePath) {
                                                                                            
                                                                                            
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 缓存大小为512KB
        factory.setSizeThreshold(524288);
        // 临时文件夹
        factory.setRepository(new File(savePath + "/temp"));
        // 初始化上传控件
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 文件大小最大3MB
        upload.setFileSizeMax(3145728);
        upload.setHeaderEncoding("UTF-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        Iterator<FileItem> it = fileList.iterator();
        String name = "";
        String filename = "";
        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                name = item.getName();
                if (name != null && !name.trim().equals("")) {
                    filename = generateFileName(name);
                    File file = new File(savePath + "/" + filename);
                    try {
                        item.write(file);
                        String imgstr = this.getServletContext()
                                .getContextPath();
                        imgstr = imgstr + "/upload/" + filename;
                        response.getWriter().write("http://localhost:8080"+imgstr);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    /*
     * 初始化文件存储路径
     */
    private String generateDir() {
        String pathString = getServletConfig().getServletContext().getRealPath(
                "/upload");
        String tempString = getServletConfig().getServletContext().getRealPath(
                "/upload/temp");
        File dirPath = new File(pathString);
        File dirTemp = new File(tempString);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        if (!dirTemp.exists()) {
            dirTemp.mkdirs();
        }
        return pathString;
    }
    /*
     * 生成文件名
     */
    private String generateFileName(String name) {
        long currentTime = System.currentTimeMillis();
        int i = (int) (Math.random() * 1000D + 1.0D);
        long result = currentTime + i;
        String filename = String.valueOf(result) + getFileExt(name);
        return filename;
    }
    /*
     * 获取文件格式
     */
    private String getFileExt(String name) {
        int pos = name.lastIndexOf(".");
        if (pos > 0) {
            return name.substring(pos);
        } else {
            return name;
        }
    }
}


至此,到你Servlet中所写的目录下查看是否有文件已经传来:

211839619.jpg


至此,利用组将实现文件上传,其本质这个组件并没有实现文件的上传,自己必须亲自写好上传的业务逻辑,组件只是简化并是上传界面友好罢了!只要组件的参数和方法使用恰当,便能自定义许多其他属性;

   这个仅仅是一个开始,接下来还要将上传来的图片进行预览剪切,这时候会用到其他的jQuery组件,达到类似于论坛更换剪切头像的目的;