文件上传,及导入,导出

这几天做了文件上传,导入Excel,写入Excel,在平时项目中都是比较常用的。我这里做了文件上传后直接显示到页面上

1、文件上传,需要commons.fileupload-1.2.0.jar、commons.io-1.4.0.jar两个jar包,实现如下效果,文件上传我这里介绍两种方法,一是就用FileItem上传,二是io流写入-转换成字节码上传,实现方法Java类中介绍。



文件上传,及导入,导出_第1张图片

新建一个jsp,代码如下,注意:上传文件,form表单中enctype="multipart/form-data"的意思,是设置表单的MIME 编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart /form-data,才能完整的传递文件数据,进行下面的操作.
enctype="multipart/form-data"是上传二进制数据; form里面的input的值以2进制的方式传过去。

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>上传Excel</title>
        <!--这是我项目中的一个地址,<%=baseUrl%>,这个大家可以不用管,下面跳转到action地址,根据自己的来-->
      <%@ include file="/global/commonPage/includeHead/head.jsp" %>
    </head>
        function improtBudgetVersion(){
          var file=document.getElementById("fileName").value;
          //我这里是做了一个测试,只传excel文件,
          var reg=/.+\.xls/;
          if(file==""){
            alert("请选择一个导入文件")
            return;
          }
          if(!reg.test(file)){
            alert("导入文件的Excel类型只能是:xls");
            return;
          }
          //传到upImageFile类中的importExcel方法
          fileForm.action = "<%=baseUrl%>/upImageFile.do?method=importExcel";
          fileForm.submit();
        }
    </script>
    <body>
    <form action="" enctype="multipart/form-data" id="fileForm" name="fileForm"  method="post" >
      <div id="filePanel">
        <table >
          <tr>
            <td width="103px" style="font-size:10px;text-align:center"></td>
            <td><input type="file" id="fileName" name="fileName"  /></td>
            <td style="width:80px"><input type="button" value="导入"  onclick="javascript:improtBudgetVersion()"  id="import1"/></td>
            <td><input type="button" value="导出" onclick="exportClik()" id="export" style="right: auto"></td>
            <td><input type="button" onclick="search()" value="查看" ></td>
          </tr>
        </table>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<textarea  type="textarea" id="textareaId" style="width:460;height:100;" readonly="true">${msg}</textarea>
      </div>
    </body>
    </html>

    jsp写好后,新建UpImageFileAction类,代码如下:第一种用FileItem上传,代码如下:

  2. import org.apache.commons.fileupload.DefaultFileItemFactory;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.FileUpload;
    import org.apache.commons.fileupload.FileUploadException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.util.Iterator;
    import java.util.List;
    public class UpImageFileAction extends BaseDispatchAction {
    public File uploadFile(HttpServletRequest request,
                            HttpServletResponse response) throws UnsupportedEncodingException,
            FileUploadException {
        request.setCharacterEncoding("gb2312");
            response.setContentType("text/html;charset=gb2312");
            File uploadDirectoryFile = null; // 文件上传到的目录
            File tempDirectoryFile = null; // 临时文件目录
            File uploadedFile = null; // 上传的文件
            String nativeWebAppFoldPath =request.getRealPath("/");//得到文件的当前路径
            tempDirectoryFile = new File(nativeWebAppFoldPath + "tempDirectory");
            //我是把上传的文件存在c盘下面,这个你可以自己随便写
            uploadDirectoryFile = new File("C:\\Users\\Administrator\\Desktop\\upload\\");
    //        文件夹不存在就自动创建
            if (!tempDirectoryFile.exists()) {
                tempDirectoryFile.mkdirs();
            }
    // 文件夹不存在就自动创建
            if (!uploadDirectoryFile.exists()) {
                uploadDirectoryFile.mkdirs();
            }
            DefaultFileItemFactory factory = new DefaultFileItemFactory();
            factory.setSizeThreshold(1024000); // 最大内存大小
            factory.setRepository(tempDirectoryFile); // 临时目录
            FileUpload upload = new FileUpload(factory);
            upload.setSizeMax(2000000); // 设置允许上传文件大小,单位:字节
            upload.setFileItemFactory(factory);
            upload.setHeaderEncoding("UTF-8");
            try {
            //得到上传的文件
                List items = upload.parseRequest(request);
    //            创建集合迭代器,获取一个迭代器中当前位置的对象
                Iterator itr = items.iterator();
    //            判断迭代器后面是否有东西
                while (itr.hasNext()) {
    //               iter.next:当指针为空,会自动向后移
                    FileItem item = (FileItem) itr.next();
                    if (item.isFormField()) {
                        System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
                    } else {
                        if (item.getName() != null && !item.getName().equals("")) {
                            String fileName = item.getName();
                            long fileSize = item.getSize();
                            String fileType = item.getContentType();
                            System.out.println("上传文件的大小:" + fileSize);
                            System.out.println("上传文件的类型:" + fileType);
                            System.out.println("上传文件的名称:" + fileName);
      //上传文件的保存路径
                            uploadedFile = new File(uploadDirectoryFile, fileName);
                            item.write(uploadedFile);
                            System.out.println("上传成功");
                        } else {
                            System.out.println("上传失败");
                        }
                    }
                }
            }catch  (Exception e) {
            e.printStackTrace();
        }
            return uploadedFile ;
        }

    第二种,用io流-转换成字节数组上传

import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
public class UpImageFileAction extends BaseDispatchAction {
private File uploadFile(HttpServletRequest request,
                        HttpServletResponse response) throws UnsupportedEncodingException,
        FileUploadException {
    request.setCharacterEncoding("gb2312");
        response.setContentType("text/html;charset=gb2312");
        File uploadDirectoryFile = null; // 文件上传到的目录
        File tempDirectoryFile = null; // 临时文件目录
        File uploadedFile = null; // 上传的文件
        String nativeWebAppFoldPath =request.getRealPath("/");//得到文件的当前路径
        tempDirectoryFile = new File(nativeWebAppFoldPath + "tempDirectory");
        uploadDirectoryFile = new File("C:\\Users\\Administrator\\Desktop\\upload\\");
//        文件夹不存在就自动创建
        if (!tempDirectoryFile.exists()) {
            tempDirectoryFile.mkdirs();
        }
// 文件夹不存在就自动创建
        if (!uploadDirectoryFile.exists()) {
            uploadDirectoryFile.mkdirs();
        }
        DefaultFileItemFactory factory = new DefaultFileItemFactory();
        factory.setSizeThreshold(1024000); // 最大内存大小
        factory.setRepository(tempDirectoryFile); // 临时目录
        FileUpload upload = new FileUpload(factory);
        upload.setSizeMax(2000000); // 设置允许上传文件大小,单位:字节
        upload.setFileItemFactory(factory);
        upload.setHeaderEncoding("UTF-8");
        try {
        //得到上传的文件
            List items = upload.parseRequest(request);
//            创建集合迭代器,获取一个迭代器中当前位置的对象
            Iterator itr = items.iterator();
//            判断迭代器后面是否有东西
            while (itr.hasNext()) {
//               iter.next:当指针为空,会自动向后移
                FileItem item = (FileItem) itr.next();
                if (item.isFormField()) {
                    System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
                } else {
                    if (item.getName() != null && !item.getName().equals("")) {
                        String fileName = item.getName();
                        long fileSize = item.getSize();
                        String fileType = item.getContentType();
                        System.out.println("上传文件的大小:" + fileSize);
                        System.out.println("上传文件的类型:" + fileType);
                        System.out.println("上传文件的名称:" + fileName);

//把文件转换成字节数组
                  ByteArrayInputStream in = (ByteArrayInputStream) item.getInputStream();
                        byte[] buffer = new byte[1024];
                       int len = 0;
                        fileName = new File(fileName).getName();
                      fileName=uploadDirectoryFile+fileName;
                       OutputStream out =new FileOutputStream(fileName);
                          while ((len = in.read(buffer))!=-1){
                              out.write(buffer,0,len);
                           }
                
                        System.out.println("上传成功");
                    } else {
                        System.out.println("上传失败");
                    }
                }
            }
        }catch  (Exception e) {
        e.printStackTrace();
    }
        return null ;
    }
    }

  2、文件倒入,上传后导入页面,显示如下,前端我用的jsrender做的,下一篇讲解jsrender,前端代码如下

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
  String data = (String)request.getAttribute("data") ;
%>
<html>
<head>
    <title>上传Excel</title>
  <%@ include file="/global/commonPage/includeHead/head.jsp" %>
  <!--导入jqery-jar,jsrener包-->
  <script type="text/javascript" src="<%=baseUrl%>/global/scripts/jquery/jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="<%=baseUrl%>/global/scripts/jsrender.js"></script>
</head>
<script>
  function search(){
    var aaa = '<%=data%>';
    var htmlStr = $("#dataTemplate").render(JSON.parse(aaa));
    $("#dataList").html(htmlStr);
  }
    function improtBudgetVersion(){
      var file=document.getElementById("fileName").value;
      var reg=/.+\.xls/;
      if(file==""){
        alert("请选择一个导入文件")
        return;
      }
      if(!reg.test(file)){
        alert("导入文件的Excel类型只能是:xls");
        return;
      }
      fileForm.action = "<%=baseUrl%>/upImageFile.do?method=importExcel";
      fileForm.submit();
    }
</script>
<body>
<script type="text/x-jsrender" id="dataTemplate">
//薪资大于1w的显示红色,否则显示绿色
    {{if pay > 10000}}
      <tr class="g-grid-tr" style="background: red;">
        {{else}}
      <tr class="g-grid-tr" style="background: green;">
    {{/if}}
          <td class="tdEdit" style="text-align: center;">{{:#getIndex()}}:{{:name}}</td>
          <td class="tdEdit" style="text-align: center;">{{:sex}}</td>
          <td class="tdEdit" style="text-align: center;">{{:age}}</td>
          <td class="tdEdit" style="text-align: center;">{{>pay}}</td>
          <td class="tdEdit" style="text-align: center;">{{:phone}}</td>
        </tr>
</script>
<input type="button" onclick="search()" value="查看" >
<form action="" enctype="multipart/form-data" id="fileForm" name="fileForm"  method="post" >
  <div id="filePanel">
    <table >
      <tr>
        <td width="103px" style="font-size:10px;text-align:center"></td>
        <td><input type="file" id="fileName" name="fileName"  /></td>
        <td style="width:80px"><input type="button" value="导入"  onclick="javascript:improtBudgetVersion()"  id="import1"/></td>
        <td><input type="button" value="导出" onclick="exportClik()" id="export" style="right: auto"></td>
      </tr>
    </table>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<textarea  type="textarea" id="textareaId" style="width:460;height:100;" readonly="true">${msg}</textarea>
  </div>
</form>
<div class="g-panel-body" style="height: 200px; overflow-y: auto">
  <table align="center" cellpadding="0" cellspacing="1" class="table" >
    <thead class="g-grid-hd">
    <tr>
      <td class="tdTitle" style="text-align: center; width:20%" >姓名</td>
      <td class="tdTitle" style="text-align: center; width:10%">性别</td>
      <td class="tdTitle" style="text-align: center; width:10%">年龄</td>
      <td class="tdTitle" style="text-align: center; width:10%">薪资</td>
      <td class="tdTitle" style="text-align: center; width:10%">电话</td>
    </tr>
    </thead>
    <tbody id="dataList">
    </tbody>
    </table>
  </div>
</body>
</html>

 后台Java代码,用到jxl-2.6.jar包就可以了,接到上面的方法写,倒入jxl-2.6.jar,先新建一个Export实体类,如下



导入的方法代码

 import com.brainlong.framework.struts.BaseDispatchAction;
import jxl.Sheet;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.*;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import mc.global.demo.Export;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.io.*;
import java.util.Iterator;
import java.util.List;
 public ActionForward importExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)throws Exception{
    
    File file = uploadFile(request, response);
    Workbook workbook = Workbook.getWorkbook(new FileInputStream(file));
    //创建对工作表的引用
    Sheet sheet = workbook.getSheet(0);//使用索引获取第一个工作表
    System.out.println("工作表名称:"+sheet.getName());
    int rows=sheet.getRows();
    int cols=sheet.getColumns();
    System.out.println("一共"+rows+"行,"+cols+"列");
//    List<Export> obj= new ArrayList<Export>();
    JSONArray obj =new JSONArray();
    for (int i=1;i<rows;i++){
        Export export = new Export();
//            sheet.getCell(j,i).getContents();得到指定单元格的内容
//            String item =(sheet.getCell(j,i).getContents().equals("")? "":sheet.getCell(j,i).getContents()).trim();
            String name= sheet.getCell(0,i).getContents();
            String sex =sheet.getCell(1,i).getContents();
            String  age =sheet.getCell(2,i).getContents();
            String  pay=sheet.getCell(3,i).getContents();
            String  phone=sheet.getCell(4,i).getContents();
            System.out.println(name);
            System.out.println(sex);
            System.out.println(age);
            System.out.println(pay);
            System.out.println(phone);
            export.setName(name);
            export.setSex(sex);
            export.setAge(age);
            export.setPay(pay);
            export.setPhone(phone);
            obj.add(JSONObject.fromObject(export));
    }
    //返回数据源
    request.setAttribute("data", obj.toString());
    return mapping.findForward("upExcelJsp");
  }

3、导出功能的实现

jsp代码如下,我这里写的比较简单,点击导入按钮后直接跳转到action,然后在action中本地建一个excel写入

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>导入Excel</title>
 t type="text/javascript" src="<%=baseUrl%>/global/scripts/jsrender.js"></script>
</head>
<script>
   function exportClik(){
    alert(11);
    var file=document.getElementById("fileName").value;
    fileForm.action = "<%=baseUrl%>/upImageFile.do?method=exportExcel";
    fileForm.submit();
   }
</script>
<body>

<form action="" enctype="multipart/form-data" id="fileForm" name="fileForm"  method="post" >
  <div id="filePanel">
    <table >
      <tr>
        <td width="103px" style="font-size:10px;text-align:center"></td>
        <td><input type="file" id="fileName" name="fileName"  /></td>
        <td style="width:80px"><input type="button" value="导入"  onclick="javascript:improtBudgetVersion()"  id="import1"/></td>
        <td><input type="button" value="导出" onclick="exportClik()" id="export" style="right: auto"></td>
      </tr>
    </table>
  </div>
</form>
</body>
</html>

你可能感兴趣的:(文件上传,及导入,导出)