jQuery File Upload blueimp with struts2 简单试用

Official Site的话随便搜索就可以去了

另外新版PHP似乎都有问题  虽然图片都可以上传  但是response报错  我下载的是8.8.7木有问题   但是8.8.7版本结合修改main.js上传部分修改为自己的地址后天剑文件start按钮会一直灰色...

所以还是下载最新版比较好

PS帮助文档有点乱   先看这个 https://github.com/blueimp/jQuery-File-Upload/wiki/Setup

这里还有个https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin  用处不是很大  毕竟我现在只是拿来用  不分析

关于第一个连接  仔细阅读 custom server-side upload handler  这个部分

也就是要修改main.js 以及 页面中input的name值  这个input的name值要和struts中的匹配才行

另外注意一下server的返回值 custom server-side upload handler 中有说明 是一个JSON格式的值  按照它的格式来

 

不过我有点小疑问   观察官方下载的Demo  所谓的多文件上传实际上就是多次向后台发送请求而已  并不是同一个请求发送多个文件

所以服务端的返回json格式中files中总是只有一个文件....

 

main.js中地址部分改为自己的地址

    $('#fileupload').fileupload({
        disableImageResize: false,
        // Uncomment the following to send cross-domain cookies:
        //xhrFields: {withCredentials: true},
        url: 'UploadAction_handle.action'
    });

 

 上传处理Action

package action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import utils.MyUploadPic;
import utils.MyUploadPicList;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
    private static final long serialVersionUID = 572146812454l;
    private static final int BUFFER_SIZE = 16 * 1024; // 这里的BUFFER_SIZE
                                                        // 表示一个数据缓冲区是16KB
    // 所以写出的文件最小是16KB
    
    

    private File[] myFile; // myFile就是用户准备上传的文件
    private String[] myFileContentType;
    private String[] myFileFileName; // 用户上传文件的真实文件名

    // 当然了 这里的属性命名是任意的
    // 但是要保证和页面元素中的 name属性的值要匹配
    // 比如 页面中input 的name是myFile 我这里就应该有 setMyFile getMyFile
    // 为了减少出错, 属性都用对应的名字好了
    // 若文件对象的名字是xxx 文件类型就应是 xxxContentType 真实文件名则应是xxxFileName

    // private String caption;
    public File[] getMyFile() {
        return myFile;
    }

    public void setMyFile(File[] myFile) {
        this.myFile = myFile;
    }

    public String[] getMyFileContentType() {
        return myFileContentType;
    }

    public void setMyFileContentType(String[] myFileContentType) {
        this.myFileContentType = myFileContentType;
    }

    public String[] getMyFileFileName() {
        return myFileFileName;
    }

    public void setMyFileFileName(String[] myFileFileName) {
        this.myFileFileName = myFileFileName;
    }

    private String fileDir="D:/workspace/files/";

    // 为了保证上传文件不会重名
    // 文件名以当前毫秒数保存
    private String saveFileName; // 以当前毫秒数为文件名
    
    private static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
    }

    private String getFilenameWithoutExstension(String filename) {
        int pos = filename.lastIndexOf(".");
        if (pos >= 0 && pos < filename.length()) {
            return filename.substring(0, pos);
        } else {
            return "";
        }
    }


    //这是进入Action后首先执行的方法
    //前台会发送两种请求 一种是
    public String handle() throws Exception {
        System.out.println("0000000 upload !!!");
        HttpServletRequest request = ServletActionContext.getRequest();
        System.out.println("000000  request"+request.getMethod());
        HttpServletResponse response = ServletActionContext.getResponse();
        //当request的类型是DELETE时  执行删除操作
        if(request.getMethod().equals("DELETE")){
            deleteFiles(request,response);
        }else if(request.getMethod().equals("POST")){
            upload(request,response);
        }
        return null;

    }

    public String upload(HttpServletRequest request ,HttpServletResponse response ){
        MyUploadPicList files = new MyUploadPicList();
        List<MyUploadPic> list = new ArrayList<MyUploadPic>();

        for (int i = 0; i < myFile.length; i++) {
            saveFileName = getFilenameWithoutExstension(myFileFileName[i])
                    + new Date().getTime() + getExtention(myFileFileName[i]);
            // writeFile 就是以当前毫秒数为文件名的文件
            /*
             * File writeFile = new
             * File(ServletActionContext.getServletContext()
             * .getRealPath("/files") + "/" + saveFileName);
             */
            File writeFile = new File(fileDir + saveFileName);
            System.out.println("000000000   tmp " + myFile[i]);
            copy(myFile[i], writeFile);
            MyUploadPic pic = new MyUploadPic();
            try {
                pic.setSize((int) getFileSizes(myFile[i]));
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            pic.setName(saveFileName);
            // pic.setThumbnailUrl("http://localhost/jQuery-File-Upload-8.8.7/server/php/files/thumbnail/jhhbimages.jpg");
            pic.setDeleteUrl("UploadAction_handle.action?file="+saveFileName);
            pic.setDeleteType("DELETE");
            list.add(pic);

        }
        files.setFiles(list);
        PrintWriter writer=null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String jsonStr = new Gson().toJson(files);
        System.out.println(jsonStr);
        writer.print(jsonStr);
        writer.flush();
        writer.close();
        
        return null;
    }
    

    public void deleteFiles(HttpServletRequest request,HttpServletResponse response) {
        ActionContext context = ActionContext.getContext();
        Map params = context.getParameters();
        String[] myParams = (String[]) params.get("file");
        String delFileName=myParams[0];
        System.out.println("00000000   del my file name"+delFileName);
        File delFile=new File(fileDir+delFileName);
        delFile.delete();  
        
        PrintWriter writer=null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //注意观察Official Demo 删除时返回的内容是 {"待删除文件的文件名":true}
        //{"index.jpg":true}
        //有了这个response 前台就知道已经删除 就会自动消除文件
        String jsonStr="{\""+delFileName+"\":true"+"}";
        System.out.println(jsonStr);
        
        writer.print(jsonStr);
        writer.flush();
        writer.close();
        
        
        
    }

        private static void copy(File src, File dst) {
        System.out.println("000000   src dst " + src.getPath() + "   "
                + dst.getPath());
        try {
            InputStream in = null;
            OutputStream out = null;
            try {
                in = new BufferedInputStream(new FileInputStream(src),
                        BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst),
                        BUFFER_SIZE);

                // 上传的最小文件不能小于 1 KB 否则会出现找不到文件的错误
                byte[] buffer = new byte[BUFFER_SIZE];
                while (in.read(buffer) > 0) {
                    out.write(buffer);
                }

            } finally {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /* 获取文件大小 */
    public long getFileSizes(File f) throws Exception {// 取得文件大小
        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s = fis.available();
        } else {
            f.createNewFile();
            System.out.println("文件不存在");
        }
        return s;
    }


}

 

页面

Basic页面

<%@page contentType="text/html; charset=GBK" language="java"%>
<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
</head>
<body>
    
    <input id="fileupload" type="file" name="myFile" data-url="UploadAction_handle.action" multiple>
    <div id="progress">
        <div class="bar" style="width: 0%;"></div>
    </div>
    <div id="target">target</div>
    <p></p><p></p><p></p><p></p><p></p>
    
    <script>
        $('#fileupload').fileupload({
            dataType : 'json',
            done : function(e, data) {
                $.each(data.result.files, function(index, file) {
                    $('<p/>').text(file.name).appendTo(document.body);
                });
            }
        });
        $("#target").click(function() {
            alert("Handler for .click() called.");
            $('#fileupload').fileupload({
                dataType : 'json',
                done : function(e, data) {
                    $.each(data.result.files, function(index, file) {
                        $('<p/>').text(file.name).appendTo(document.body);
                    });
                }
            });
        });
    </script>
</body>
</html>

完整页面

<!DOCTYPE HTML>
<!--
/*
 * jQuery File Upload Plugin Demo 9.0.1
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */
-->
<html lang="en">
<head>
<!-- Force latest IE rendering engine or ChromeFrame if installed -->
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<meta charset="utf-8">
<title>jQuery File Upload Demo</title>
<meta name="description" content="File Upload widget with multiple file selection, drag&amp;drop support, progress bars, validation and preview images, audio and video for jQuery. Supports cross-domain, chunked and resumable file uploads and client-side image resizing. Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap styles -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<!-- Generic page styles -->
<link rel="stylesheet" href="css/style.css">
<!-- blueimp Gallery styles -->
<link rel="stylesheet" href="http://blueimp.github.io/Gallery/css/blueimp-gallery.min.css">
<!-- CSS to style the file input field as button and adjust the Bootstrap progress bars -->
<link rel="stylesheet" href="css/jquery.fileupload.css">
<link rel="stylesheet" href="css/jquery.fileupload-ui.css">
<!-- CSS adjustments for browsers with JavaScript disabled -->
<noscript><link rel="stylesheet" href="css/jquery.fileupload-noscript.css"></noscript>
<noscript><link rel="stylesheet" href="css/jquery.fileupload-ui-noscript.css"></noscript>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-fixed-top .navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="https://github.com/blueimp/jQuery-File-Upload">jQuery File Upload</a>
        </div>
        <div class="navbar-collapse collapse">
            <ul class="nav navbar-nav">
                <li><a href="https://github.com/blueimp/jQuery-File-Upload/tags">Download</a></li>
                <li><a href="https://github.com/blueimp/jQuery-File-Upload">Source Code</a></li>
                <li><a href="https://github.com/blueimp/jQuery-File-Upload/wiki">Documentation</a></li>
                <li><a href="https://blueimp.net">&copy; Sebastian Tschan</a></li>
            </ul>
        </div>
    </div>
</div>
<div class="container">
    <h1>jQuery File Upload Demo</h1>
    <h2 class="lead">Basic Plus UI version</h2>
    <ul class="nav nav-tabs">
        <li><a href="basic.html">Basic</a></li>
        <li><a href="basic-plus.html">Basic Plus</a></li>
        <li class="active"><a href="index.html">Basic Plus UI</a></li>
        <li><a href="angularjs.html">AngularJS</a></li>
        <li><a href="jquery-ui.html">jQuery UI</a></li>
    </ul>
    <br>
    <blockquote>
        <p>File Upload widget with multiple file selection, drag&amp;drop support, progress bars, validation and preview images, audio and video for jQuery.<br>
        Supports cross-domain, chunked and resumable file uploads and client-side image resizing.<br>
        Works with any server-side platform (PHP, Python, Ruby on Rails, Java, Node.js, Go etc.) that supports standard HTML form file uploads.</p>
    </blockquote>
    <br>
    <!-- The file upload form used as target for the file upload widget -->
    <form id="fileupload" action="//jquery-file-upload.appspot.com/" method="POST" enctype="multipart/form-data">
        <!-- Redirect browsers with JavaScript disabled to the origin page -->
        <noscript><input type="hidden" name="redirect" value="http://blueimp.github.io/jQuery-File-Upload/"></noscript>
        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
                <!-- The fileinput-button span is used to style the file input field as button -->
                <span class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <span>Add files...</span>
                    <input type="file" name="myFile" multiple>
                </span>
                <button type="submit" class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start upload</span>
                </button>
                <button type="reset" class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel upload</span>
                </button>
                <button type="button" class="btn btn-danger delete">
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" class="toggle">
                <!-- The global file processing state -->
                <span class="fileupload-process"></span>
            </div>
            <!-- The global progress state -->
            <div class="col-lg-5 fileupload-progress fade">
                <!-- The global progress bar -->
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <!-- The extended global progress state -->
                <div class="progress-extended">&nbsp;</div>
            </div>
        </div>
        <!-- The table listing the files available for upload/download -->
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>
    <br>
    <div class="panel panel-default">
        <div class="panel-heading">
            <h3 class="panel-title">Demo Notes</h3>
        </div>
        <div class="panel-body">
            <ul>
                <li>The maximum file size for uploads in this demo is <strong>5 MB</strong> (default file size is unlimited).</li>
                <li>Only image files (<strong>JPG, GIF, PNG</strong>) are allowed in this demo (by default there is no file type restriction).</li>
                <li>Uploaded files will be deleted automatically after <strong>5 minutes</strong> (demo setting).</li>
                <li>You can <strong>drag &amp; drop</strong> files from your desktop on this webpage (see <a href="https://github.com/blueimp/jQuery-File-Upload/wiki/Browser-support">Browser support</a>).</li>
                <li>Please refer to the <a href="https://github.com/blueimp/jQuery-File-Upload">project website</a> and <a href="https://github.com/blueimp/jQuery-File-Upload/wiki">documentation</a> for more information.</li>
                <li>Built with Twitter's <a href="http://twitter.github.com/bootstrap/">Bootstrap</a> CSS framework and Icons from <a href="http://glyphicons.com/">Glyphicons</a>.</li>
            </ul>
        </div>
    </div>
</div>
<!-- The blueimp Gallery widget -->
<div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even">
    <div class="slides"></div>
    <h3 class="title"></h3>
    <a class="prev"></a>
    <a class="next"></a>
    <a class="close">×</a>
    <a class="play-pause"></a>
    <ol class="indicator"></ol>
</div>
<!-- The template to display files available for upload -->
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-upload fade">
        <td>
            <span class="preview"></span>
        </td>
        <td>
            <p class="name">{%=file.name%}</p>
            <strong class="error text-danger"></strong>
        </td>
        <td>
            <p class="size">Processing...</p>
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="progress-bar progress-bar-success" style="width:0%;"></div></div>
        </td>
        <td>
            {% if (!i && !o.options.autoUpload) { %}
                <button class="btn btn-primary start" disabled>
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start</span>
                </button>
            {% } %}
            {% if (!i) { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<!-- The template to display files available for download -->
<script id="template-download" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
    <tr class="template-download fade">
        <td>
            <span class="preview">
                {% if (file.thumbnailUrl) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery><img src="{%=file.thumbnailUrl%}"></a>
                {% } %}
            </span>
        </td>
        <td>
            <p class="name">
                {% if (file.url) { %}
                    <a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}>{%=file.name%}</a>
                {% } else { %}
                    <span>{%=file.name%}</span>
                {% } %}
            </p>
            {% if (file.error) { %}
                <div><span class="label label-danger">Error</span> {%=file.error%}</div>
            {% } %}
        </td>
        <td>
            <span class="size">{%=o.formatFileSize(file.size)%}</span>
        </td>
        <td>
            {% if (file.deleteUrl) { %}
                <button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}>
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" name="delete" value="1" class="toggle">
            {% } else { %}
                <button class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel</span>
                </button>
            {% } %}
        </td>
    </tr>
{% } %}
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included -->
<script src="js/vendor/jquery.ui.widget.js"></script>
<!-- The Templates plugin is included to render the upload/download listings -->
<script src="http://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>
<!-- The Load Image plugin is included for the preview images and image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Load-Image/js/load-image.min.js"></script>
<!-- The Canvas to Blob plugin is included for image resizing functionality -->
<script src="http://blueimp.github.io/JavaScript-Canvas-to-Blob/js/canvas-to-blob.min.js"></script>
<!-- Bootstrap JS is not required, but included for the responsive demo navigation -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<!-- blueimp Gallery script -->
<script src="http://blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js"></script>
<!-- The Iframe Transport is required for browsers without support for XHR file uploads -->
<script src="js/jquery.iframe-transport.js"></script>
<!-- The basic File Upload plugin -->
<script src="js/jquery.fileupload.js"></script>
<!-- The File Upload processing plugin -->
<script src="js/jquery.fileupload-process.js"></script>
<!-- The File Upload image preview & resize plugin -->
<script src="js/jquery.fileupload-image.js"></script>
<!-- The File Upload audio preview plugin -->
<script src="js/jquery.fileupload-audio.js"></script>
<!-- The File Upload video preview plugin -->
<script src="js/jquery.fileupload-video.js"></script>
<!-- The File Upload validation plugin -->
<script src="js/jquery.fileupload-validate.js"></script>
<!-- The File Upload user interface plugin -->
<script src="js/jquery.fileupload-ui.js"></script>
<!-- The main application script -->
<script src="js/main.js"></script>
<!-- The XDomainRequest Transport is included for cross-domain file deletion for IE 8 and IE 9 -->
<!--[if (gte IE 8)&(lt IE 10)]>
<script src="js/cors/jquery.xdr-transport.js"></script>
<![endif]-->
</body> 
</html>

 

另外两个utils中的类   

MyUploadPic是上传的每一张图片的信息  

MyUploadPicList 是上传的一系列图片信息   包括文件总大小等等

package utils;
public class MyUploadPic {

    String name;
    int size;
    String url;
    String thumbnailUrl;
    String deleteUrl;
    String     deleteType;
    String error;
    
    public MyUploadPic(){
        
    }
    
    
    public MyUploadPic(String name, int size, String url,
            String thumbnailUrl, String deleteUrl, String deleteType,String error) {
        super();
        this.name = name;
        this.size = size;
        this.url = url;
        this.thumbnailUrl = thumbnailUrl;
        this.deleteUrl = deleteUrl;
        this.deleteType = deleteType;
        this.error=error;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSize() {
        return size;
    }
    public void setSize(int size) {
        this.size = size;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getThumbnailUrl() {
        return thumbnailUrl;
    }
    public void setThumbnailUrl(String thumbnailUrl) {
        this.thumbnailUrl = thumbnailUrl;
    }
    public String getDeleteUrl() {
        return deleteUrl;
    }
    public void setDeleteUrl(String deleteUrl) {
        this.deleteUrl = deleteUrl;
    }
    public String getDeleteType() {
        return deleteType;
    }
    public void setDeleteType(String deleteType) {
        this.deleteType = deleteType;
    }


    public String getError() {
        return error;
    }


    public void setError(String error) {
        this.error = error;
    }

    
    
}

 

package utils;
import java.util.List;


public class MyUploadPicList {

    public MyUploadPicList(){
        
    }
    
    List<MyUploadPic> files;

    public List<MyUploadPic> getFiles() {
        return files;
    }

    public void setFiles(List<MyUploadPic> files) {
        this.files = files;
    }
    
    
}

 

 

posted @ 2014-01-03 15:35  cart55free99  阅读(2288)  评论(0编辑  收藏  举报