• struts2多文件上传(带进度条)demo+说明


    利用plupload插件实现多文件上传,实现图片:

    在jsp写入js代码:

    z<%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@ taglib prefix="s" uri="/struts-tags"%>
    
    
    <html> 
    <head><title>test</title> 
    
    <style type="text/css">@import url(plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css);</style>
    <script src="js/jquery-1.6.2.min.js" type="text/javascript"></script> 
    <script type="text/javascript" src="plupload/js/plupload.full.js"></script>
    <script type="text/javascript" src="plupload/js/jquery.plupload.queue/jquery.plupload.queue.js"></script>
    <script type="text/javascript" src="plupload/js/i18n/cn.js"></script>
    <script type="text/javascript">
    // Convert divs to queue widgets when the DOM is ready
        $(function() {
            $("#uploader").pluploadQueue({
                // General settings
                runtimes : 'gears,flash,silverlight,browserplus,html5,html4',
                url : 'FileUpload.action',
                max_file_size : '10mb',
                unique_names : true,
                multiple_queues : true,
                chunk_size: '2mb',
                // Specify what files to browse for
                filters : [
                    {title : "xls, xlsx文档", extensions : "xls,xlsx"}
                ],
        
                // Flash settings
                flash_swf_url : 'plupload/js/plupload.flash.swf',
                // Silverlight settings
                silverlight_xap_url : 'plupload/js/plupload.silverlight.xap'
            });
            $('form').submit(function(e) {
                var uploader = $('#uploader').pluploadQueue();
                if (uploader.files.length > 0) {
                    // When all files are uploaded submit form
                    uploader.bind('StateChanged', function() {
                        if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
                            $('form')[0].submit();
                        }
                    });
                    uploader.start();
                } else {
                    alert('请先上传数据文件.');
                }
                return false;
            });
        });
        
        
    </script>
    
    </head>
    
    <body>
        <div>
            <div style=" 750px; margin: 0px auto">
                <form id="formId" action="Submit1.action" method="post">
                    <div id="uploader">
                        <p>您的浏览器未安装 Flash, Silverlight, Gears, BrowserPlus 或者支持 HTML5 .</p>
                    </div>
                    <input type="submit" value="完成"/>
                </form>
            </div>
        </div>
    </body>
    
    </html>

    注:js,css引用路径需修改为自己项目路径。

    FileAction文件上传类:

    package com.action;
    
    import java.io.*;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts2.ServletActionContext;
    import com.opensymphony.xwork2.ActionSupport;
    
    
    public class FileAction extends ActionSupport {
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
    
        private static final int BUFFER_SIZE = 2 * 1024;
    
        private int id = -1;
    
        private File upload;
        private String name;
        private List<String> names;
        private String uploadFileName;
        //文件类型
        private String uploadContentType;
        //大文件上传 分块chul
        private int chunk;
        private int chunks;
        
        private String result;
    
    
        private void copy(File src, File dst) {
            InputStream in = null;
            OutputStream out = null;
            try {
                if (dst.exists()) {
                    out = new BufferedOutputStream(new FileOutputStream(dst, true),
                            BUFFER_SIZE);
                } else {
                    out = new BufferedOutputStream(new FileOutputStream(dst),
                            BUFFER_SIZE);
                }
                in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
    
                byte[] buffer = new byte[BUFFER_SIZE];
                int len = 0;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (null != in) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (null != out) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        public String upload() throws Exception {
    
            String dstPath = ServletActionContext.getServletContext().getRealPath(
                    "resources\files")
                    + "\" + this.getName();
            File dstFile = new File(dstPath);
    
            // 文件已存在(上传了同名的文件)
            if (chunk == 0 && dstFile.exists()) {
                dstFile.delete();
                dstFile = new File(dstPath);
            }
    
            copy(this.upload, dstFile);
            System.out.println("上传文件:" + uploadFileName + " 临时文件名:" + uploadContentType + " "
                    + chunk + " " + chunks);
            if (chunk == chunks - 1) {
                // 完成一整个文件;
            }
    
            return "success";
        }
    
        public String submit() {
            String filePath = ServletActionContext.getServletContext().getRealPath(
                    "resources\files");
            System.out.println("保存文件路径: " + filePath);
            
            HttpServletRequest request = ServletActionContext.getRequest();
            
            result =  "";
            int count = Integer.parseInt(request.getParameter("uploader_count"));
            for (int i = 0; i < count; i++) {
                uploadFileName = request.getParameter("uploader_" + i + "_name");
                name = request.getParameter("uploader_" + i + "_tmpname");
                System.out.println(uploadFileName + " " + name);
                try {
                    //do something with file;
                    result += uploadFileName + "导入完成. <br />";  
                } catch(Exception e) {
                    result += uploadFileName + "导入失败:" + e.getMessage() + ". <br />";
                    e.printStackTrace();
                }
            }
            return "success";
        }
    
        
        public void setId(int id) {
            this.id = id;
        }
    
        public int getId() {
            return id;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getName() {
            return name;
        }
    
        public void setNames(List<String> names) {
            this.names = names;
        }
    
        public List<String> getNames() {
            return names;
        }
    
        public File getUpload() {
            return upload;
        }
    
        public void setUpload(File upload) {
            this.upload = upload;
        }
    
        public String getUploadFileName() {
            return uploadFileName;
        }
    
        public void setUploadFileName(String uploadFileName) {
            this.uploadFileName = uploadFileName;
        }
    
        public String getUploadContentType() {
            return uploadContentType;
        }
    
        public void setUploadContentType(String uploadContentType) {
            this.uploadContentType = uploadContentType;
        }
    
        public int getChunk() {
            return chunk;
        }
    
        public void setChunk(int chunk) {
            this.chunk = chunk;
        }
    
        public int getChunks() {
            return chunks;
        }
    
        public void setChunks(int chunks) {
            this.chunks = chunks;
        }
    
    
        public void setResult(String result) {
            this.result = result;
        }
    
        public String getResult() {
            return result;
        }
    
    }

    struts.xml代码:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
    <struts>
            <constant name="struts.multipart.maxSize" value="1073741824" />
        <!-- 设置Web应用的默认编码集为gbk -->
        <constant name="struts.i18n.encoding" value="utf-8"/>
        <!-- 设置Web应用的默认Locale为zh_CN -->
        <constant name="struts.locale" value="zh_CN" />
        <!-- 设置Struts2应用的国际化资源文件,多个文件中间可用逗号分隔 -->
        <constant name="struts.custom.i18n.resources" value="messageResource"/>
        <!-- 设置Struts2应用是否处于开发模式,通常在开发调试阶段设为true,正式上线后可设为false -->
        <constant name="struts.devMode" value="true" />
        <!-- 设置Struts2的默认主题为simple -->
        <constant name="struts.ui.theme" value="simple" />
        <package name="struts" extends="struts-default" namespace="/">
            <action name="FileUpload" class="com.action.FileAction" method="upload">            
                <result name="success">/result.jsp</result>
            </action>
            <action name ="Submit1" class ="com.action.FileAction" method="submit">
                   <param name="savePath">/resources/files</param>
                <result name ="success">/result.jsp</result>
            </action >
        </package>
    
    </struts>    

    欢迎大家提出问题,共同讨论。

  • 相关阅读:
    Codeforces 543E. Listening to Music
    UOJ #138. 【UER #3】开学前的涂鸦
    bzoj 3569: DZY Loves Chinese II
    bzoj 2428: [HAOI2006]均分数据
    bzoj 4589: Hard Nim
    UOJ #119. 【UR #8】决战圆锥曲线
    spoj5973
    codeforces555E
    poj1275
    bzoj4152
  • 原文地址:https://www.cnblogs.com/tobey/p/4533642.html
Copyright © 2020-2023  润新知