extjs3.2+struts2实现多文件上传excel并插入到数据库

来源:互联网 发布:淘宝天猫不能改价格吗 编辑:程序博客网 时间:2024/06/16 13:26
多个文件上传分为List集合和数组,下面我们着重介绍一下list集合的上传。都大同小异。

下面是extjs效果图

上传成功后的效果图

下面是extjs的实现代码

Ext.onReady(function() {    //音乐上传信息    Ext.BLANK_IMAGE_URL = "/extjs/images/s.gif";        var music=[                    {                        name : 'worksId',                        type : 'integer',                        sortable : true                    },                    {                        name : "isbn",                        type : "string",                        sortable : true                    }, {                        name : "name",                        type : "string",                        sortable : true                    }, {                        name : "author",                        type : "string",                        sortable : true                    }, {                        name : "description",                        type : "string",                        sortable : true                    }, {                        name : "publish",                        type : "string",                        sortable : true                    },{                        name : "price",                        type : "float",                        sortable : true                    },                    {                        name : "number",                        type : "integer",                        sortable : true                    }, {                                                name : "telecom",                        type : "string",                        sortable : true                    },{                        name : "move",                        type : "string",                        sortable : true                    }                    ,{                        name : "link",                        type : "string",                        sortable : true                    },{                        name : "web",                        type : "string",                        sortable : true                    },{                        name : "webname",                        type : "string",                        sortable : true                    },{                        name : "exclusive",                        type : "string",                        sortable : true                    },{                        name : "copyright",                        type : "string",                        sortable : true                    },{                        name : "sublicense",                        type : "string",                        sortable : true                    },{                        name : "pname",                        type : "string",                        sortable : true                    },{                        name : "accredit",                        type : "string",                        sortable : true                    },{                        name : "Btime",                        type : "string",                        sortable : true                    }            ];            var store = new Ext.data.JsonStore({            url: "findByName.action",            type:'json',           // root: 'root',            timeout: '180000',                       fields: music           // autoLoad : {params:{start:0,limit:10}}        })                var form = new Ext.form.FormPanel({                           labelWidth: 80,               url:'/extjs/upload.action',              fileUpload:true,              defaultType: 'textfield',                    items: [{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                  allowBlank: false,                                 anchor: '90%'  // anchor width by percentage              },{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                                              anchor: '90%'  // anchor width by percentage              },{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                                                 anchor: '90%'  // anchor width by percentage              },{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                                                 anchor: '90%'  // anchor width by percentage              },{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                                                 anchor: '90%'  // anchor width by percentage              },{                  xtype: 'textfield',                  fieldLabel: '上传文件',                  name: 'urlName',                  inputType: 'file',                                               anchor: '90%'  // anchor width by percentage              }]          });          var up=new Ext.Window({            width:500,            height:250,            id:'up',            frame : true,            closable:false,            items:form,                     buttons: [{                      text: '上传',                      handler: function() {                          if(form.form.isValid()){                              form.getForm().submit({                                      waitMsg:'正在上传,请稍后!',                                success: function(form, action){                                                                  var win = Ext.getCmp("up");                                 win.hide();                                 Ext.Msg.alert("提示","上传成功!");                                                                  var grid = Ext.getCmp("musicgrid");                                 var store = grid.getStore();                                 store.load();                                                                                                },                                     failure: function(){                                          Ext.Msg.alert("提示","上传失败!");                                   }                              })                                       }                     }                  },{                      text: '关闭',                      handler:function(){up.hide();}                  }]                                });            var grid = new Ext.grid.GridPanel({               id:'musicgrid',             name:'musicgrid',             renderTo : "form1",// 呈现                       // 下面的每一列都对应上面定义的列名              height:600,            width:900,            frame:true,                       tbar : [ {                xtype : 'button',                text : '上传',                iconCls : 'table_print',                id : 'upload',                handler : function() {                up.show();            }            }],             store : store,              columns: [ {header: " 序号", width: 160, sortable: true, dataIndex: 'worksId'},                 {header: "ISBN", width: 160, sortable: true, dataIndex: 'isbn'},                        {header: "作品名称", width: 160, sortable: true, dataIndex: 'name'},                        {header: "作者", width: 100, sortable: true, dataIndex: 'author'},                        {header: "是否出版", width: 100, sortable: true, dataIndex: 'publish',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }},                        {header: "出版社", width: 100, sortable: true,  dataIndex: 'pname'},                        {header: "价格", width:100, sortable: true,  dataIndex: 'price'},                        {header: "印刷份数", width: 100, sortable: true,  dataIndex: 'number'},                        {header: "作者授权", width:100, sortable: true,  dataIndex: 'accredit',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }},                         {header: "电信", width:100, sortable: true,  dataIndex: 'telecom',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }}, {header: "移动", width:100, sortable: true,  dataIndex: 'move',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }}, {header: "联通", width:100, sortable: true,  dataIndex: 'link',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }}, {header: "网站", width:100, sortable: true,  dataIndex: 'web',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }},                        {header: "网站名称", width:100, sortable: true,  dataIndex: 'webname'},                         {header: "独家性", width:100, sortable: true,  dataIndex: 'exclusive',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }}, {header: "电子版全", width:100, sortable: true,  dataIndex: 'copyright',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }}, {header: "转授权", width:100, sortable: true,  dataIndex: 'sublicense',renderer: function(value, metaData, record, rowIndex, colIndex, store, view) {                            if(value == 'Y') {                                 return "<span style='color:red;font-weight:bold;'>是</span>"                         }                             if(value == 'N') {                            return "<span style='color:green;font-weight:bold;'>否</span>"                    }                                                   }},    {header: "描述", width: 160, sortable: true, dataIndex: 'description'},                                            ]        });  });


struts2的实现代码

package com.ising99.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.List;import javax.servlet.http.HttpServletResponse;import jxl.Cell;import jxl.Sheet;import jxl.Workbook;import jxl.read.biff.BiffException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.ising99.biz.BookBiz;import com.ising99.pojo.Book;public class BookAction extends BaseAction<Book>{                        private BookBiz bookBizImpl;            //            private File urlName;                //        private String urlNameContentType;            //            private String  urlNameFileName;                        private String savePath;                        // 上传多个文件的集合文本                                                    private List<File> urlName;                          // /多个上传文件的类型集合                          private List<String> urlNameContentType;                         // 多个上传文件的文件名集合                          private List<String> urlNameFileName;                          public List<File> getUrlName() {                            return urlName;                        }                        public void setUrlName(List<File> urlName) {                            this.urlName = urlName;                        }                        public List<String> getUrlNameContentType() {                            return urlNameContentType;                        }                        public void setUrlNameContentType(List<String> urlNameContentType) {                            this.urlNameContentType = urlNameContentType;                        }                        public List<String> getUrlNameFileName() {                            return urlNameFileName;                        }                        public void setUrlNameFileName(List<String> urlNameFileName) {                            this.urlNameFileName = urlNameFileName;                        }                private     List<Book> list=new ArrayList<Book>();                                        public List<Book> getList() {                    return list;                }                public void setList(List<Book> list) {                    this.list = list;                }                        private List file;                                            public List getFile() {                            return file;                        }                        public void setFile(List file) {                            this.file = file;                        }                        public String getSavePath() {                            return savePath;                        }                        public void setSavePath(String savePath) {                            this.savePath = savePath;                        }                        public BookBiz getBookBizImpl() {                            return bookBizImpl;                        }                        public void setBookBizImpl(BookBiz bookBizImpl) {                            this.bookBizImpl = bookBizImpl;                        }                        public String upload() throws BiffException, IOException{                                                    if (null != getSession().getAttribute("book")) {                                    getSession().removeAttribute("book");                                }                                                                                            String path = ServletActionContext.getServletContext().getRealPath(                                        "excel");// 写到指定路径                                System.out.println(path);                                File file = new File(path);                                                                // 判断指定的路径下是否有urlNameFileName,如果没有,自动创建                                                                   if (!file.exists()) {                                            file.mkdirs();                                        }                                       for (int i = 0; i < urlName.size(); i++) {                                             try {                                                                                  //list集合通过get(i)的方式来获取索引                                                                                  FileUtils.copyFile(urlName.get(i), new File(file, urlNameFileName.get(i)));                                                                               } catch (IOException e) {                                                                                  // TODO Auto-generated catch block                                                                                  e.printStackTrace();                                             }                                         }                                          /*try {                                            FileUtils.copyFile(urlName, new File(file, urlNameFileName));                                        } catch (IOException e) {                                            e.printStackTrace();                                        }*/                                       for (int k = 0; k < urlNameFileName.size(); k++) {                                                                                                    String name = urlNameFileName.get(k);                                System.out.println(name);                                                                    int isa = name.lastIndexOf(".");                                    System.out.println(isa);                                    String sub = name.substring(isa + 1);                                    System.out.println(sub);                                                                                        if (!"xls".equals(sub)) {                                    HttpServletResponse response = ServletActionContext                                            .getResponse();                                    response.setContentType("text/html;charset=UTF-8");                                    response.setCharacterEncoding("UTF-8");                                    try {                                        PrintWriter out = response.getWriter();                                        out                                                .println("<script type='text/javascript' language='javascript'>");                                        out.println("alert('对不起,您选择的文档不符合上传格式,请重新选择')");                                        out.println("</script>");                                    } catch (IOException e) {                                        e.printStackTrace();                                    }                                    return null;                                } else if ("xls".equals(sub) || "xls" == sub) {                                                                        InputStream is = new FileInputStream(path + "/" + name);                                    System.out.println(path + "/" + name);                                    jxl.Workbook rwb = Workbook.getWorkbook(is);                                    Sheet sheet = rwb.getSheet(0);                                        int colNum = sheet.getColumns();//获取总列数                                        int rowNum = sheet.getRows();//获取总行数                                        for (int i =1; i < rowNum; i++) {                                            Book book =new Book();                                            for (int j = 0; j < colNum; j++) {                                                Cell c = sheet.getCell(j, i);                                                if (j == 0) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setIsbn(c.getContents());                                                        }                                                                                                    } else if(j==1)                                                {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setName(c.getContents());                                                        }                                                                                                    }else if (j == 2) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setAuthor(c.getContents());                                                    }                                                                                                } else if (j == 3) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setDescription(c.getContents());                                                    }                                                                                                } else if (j == 4) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setPublish(c.getContents());                                                    }                                                                                                                                                    } else if (j == 5) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setPname(c.getContents());                                                    }                                                                                                                                                    } else if (j ==6) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        float price=Float.parseFloat(c.getContents());                                                        book.setPrice(price);                                                    }                                                                                            } else if (j == 7) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        System.out                                                        .println(c.getContents()+"份数");                                                int number=Integer.parseInt(c.getContents());                                            book.setNumber(number);                                                    }                                                                                                                                                        } else if (j == 8) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setAccredit(c.getContents());                                                    }                                                } else if (j == 9) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                    book.setTelecom(c.getContents());                                                    }                                                }  else if (j == 10) {                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                        book.setMove(c.getContents());                                                        }                                                                                                        }  else if (j == 11) {                                                        if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                            book.setLink(c.getContents());                                                            }                                                                                                            }  else if (j == 12) {                                                            if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                                book.setWeb(c.getContents());                                                                }                                                                                                                                                                                    }  else if (j == 13) {                                                                if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                                    book.setWebname(c.getContents());                                                                    }                                                                                                                                                                                                }  else if (j == 14) {                                                                    if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                                        book.setExclusive(c.getContents());                                                                        }                                                                                                                                                                                                        }  else if (j == 15) {                                                                        if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                                            book.setCopyright(c.getContents());                                                                            }                                                                                                                                                }  else if (j == 16) {                                                                            if (null!=c.getContents()&&!"".equals(c.getContents())) {                                                                                book.setSublicense(c.getContents());                                                                                }                                                                                                                                                                                                                                }                                                                                        Date date =new Date();                                                        book.setBtime(date);                                            }                                                                                                                                        this.bookBizImpl.save(book);                                                                                                    list.add(book);                                                super.getSession().setAttribute("list", list);                                                                                                                                        }                                            }                                                                                                                }                                return SUCCESS;                                                                                             }                                                                                        public String findByName() {                            System.out.println("dddd");                            return SUCCESS;                        }            }


struts.xml

 

<action name="upload" class="bookAction" method="upload">            <result name="success">true.jsp</result>        </action>        <action name="findByName" class="bookAction" method="findByName">            <result name="success">            booklist.jsp                        </result>                    </action>

前台接收上传的数据是通过jsp接收session来获得的,下面是jsp接收session代码

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%><%@page import="com.ising99.pojo.Book"%><%@page import="net.sf.json.JSONArray"%><%    System.out.println("-------------------------");    List<Book> list=(List<Book>)session.getAttribute("list");    response.getWriter().write(JSONArray.fromObject(list).toString());        //int sizes=(Integer)session.getAttribute("size");    //response.getWriter().write("{\"list2\":"+JSONArray.fromObject(sizes).toString()+",");     %>


项目下载地址:

http://download.csdn.net/detail/wang623145708/7481015


张北论坛www.zhangbeibbs.com
邢台论坛www.hbxtbbs.com

0 0
原创粉丝点击