Java文件上传下载

在项目开发中,我们经常会用到文件的上传和下载,尤其是excel文件的上传和下载,本文介绍excel在java里头的上传和下载的使用

一、文件的下载

Java端代码:

    @RequestMapping(value="loadUserFile.do")
    @ResponseBody
    public void LoadFile(HttpServletRequest request,HttpServletResponse response) throws Exception{
          String path=this.getClass().getResource("/").getPath();//得到d:/tomcat/webapps/工程名WEB-INF/classes/路径  
                    path=path.substring(0, path.indexOf("WEB-INF/classes"));//从路径字符串中取出工程路径
                    path=path+"resources/appframe/user-template/"+"userInfo.xls";
         String suffix = path.substring(path.lastIndexOf("."));
         String file_name = path.substring(path.lastIndexOf("/") + 1);
         if (suffix.indexOf("doc") > 0) {
             response.setContentType("application/msword;charset=UTF-8");
         } else if (".xls".equals(suffix)) {
             response.setContentType("application/vnd.ms-excel application/x-excel");
         } else {
             response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
         }
      
         response.setHeader("Content-Disposition","inline;filename="+new String(file_name.getBytes("gb2312"), "ISO-8859-1"));
         // 读取要下载的文件,保存到文件输入流
         FileInputStream in = new FileInputStream(path);
         // 创建输出流
         OutputStream out = response.getOutputStream();
         // 创建缓冲区
         byte buffer[] = new byte[1024];
         int len = 0;
         // 循环将输入流中的内容读取到缓冲区当中
         while ((len = in.read(buffer)) > 0) {
          // 输出缓冲区的内容到浏览器,实现文件下载
          out.write(buffer, 0, len);
         }
         // 关闭文件输入流
         in.close();
         // 关闭输出流
         out.close();
    }

jsp端的写法:定义一个隐藏的表单即可

<form id="downloadFile" style="display:none" method="post" action="platform/appframe/afauser/loadUserFile.do">

</form>
<input type="button" id="downBtn" style="width:200px;height:30px;" value="模板下载">

js端写法:可以定义一个按钮,点击按钮的时候,触发事件

  $("#downBtn").click(function(){
var form=$A("#downloadFile");
form.submit();
})

二、文件的上传

jsp:定义一些操作按钮、定义一个表单、定义一个隐藏的iframe提交使用。

<div class="dlg-box-head">
    <div class="dlg-box-head-left" id="dragTarget">
        <span class="dlg-box-head-title" id="dlg-head-title">批量用户导入</span>
        <span class="dlg-box-head-text" id="dlg-head-action"></span>
    </div>
    <div class="dlg-box-head-right">
        <af:btnarea id="btns" displayType="DIALOG">
            <af:button id="afauser_downBtn" name="模板下载" icon="download48"
                iconMode="TOP" css="hidden"></af:button>
            <af:button id="afauser_saveBtn" name="保存" icon="save48"
                iconMode="TOP" css="hidden"></af:button>
            <af:button id="afauser_closeBtn" name="关闭" icon="close48"
                iconMode="TOP" css="hidden"></af:button>
        </af:btnarea>
    </div>
</div>

<div class="dialog-content" id="user_win">
    <div id="user_div" style="width:90%;position:relative;">
        <form  id="uploadExcelForm" name="file" action="platform/appframe/afauser/batchAdd.do" method="post" enctype="multipart/form-data" target="userFile" style="height:40px;">
            <table style="width:90%;margin-top:60px;margin-left:50px;" >
                <tr>
                    <td style="height:40px;">
                        <input id="filename" name="userFile" type="file" style="width:440px; border-bottom:1px solid #ccc;" />
                        <p style="color:#aaa; line-height:33px; text-align:left;">注:请上传excel类型的文件(.xls),一次导入数据建议不超过5000条</p>
                    </td>
                </tr>
            </table>
        </form>
        <div style="margin-top:22px;">
            <iframe name="userFileIframe" id="userFile" style="width:0px;height:0px;"></iframe>
        </div>
        
         <form id="downloadFile" style="display:none" method="post" action="platform/appframe/afauser/loadUserFile.do">

         </form>

    </div> 
</div>

js里头的写法 ,这里采用了jQuery.Form.js,同时在iframe里头进行文件的提交,避免页面的跳转:

     click:function(){
//文件类型的判断
var fileName=$("#filename").val(); if(fileName==""||fileName.indexOf(".xls")<0){ $a.messager.warn("请上传excel格式的文件!"); return false; } var form=$A("#uploadExcelForm"); var url = form.prop("action"); var options = { url: url, type:'post', success:function(data){ //成功之后的操作 }, complete:function(xhr){
              //完成后的操作,这个操作在success之后
var obj = JSON.parse(xhr["responseText"]); if(obj.statusCode==300){ $a.messager.error(obj.message); }else{ $a.messager.correct(obj.message); } }, error: function(xhr,status,msg){                //失败的操作 } }; $A("#uploadExcelForm").ajaxSubmit(options); }

备注说明下:

target 属性规定在何处打开 action URL。
<form target="_blank|_self|_parent|_top|framename">

   值          描述
_blank       在新窗口中打开。
_self        默认。在相同的框架中打开。
_parent      在父框架集中打开。
_top         在整个窗口中打开。
framename    在指定的框架中打开。 

ExcelUtil,解析excel里头的文件信息。采用poi进行excel的读写操作

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.bosssoft.platform.job.server.core.model.JobInfo;

public class ExcelHelper {
    //总行数
    private int totalRows = 0;
    //总条数
    private int totalCells = 0;
    //错误信息接收器
    private String errorMsg;
    //构造方法
    public ExcelHelper(){}
    //获取总行数
    public int getTotalRows()  { return totalRows;}
    //获取总列数
    public int getTotalCells() {  return totalCells;}
    //获取错误信息
    public String getErrorInfo() { return errorMsg; }
    
    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath){
        if (filePath == null || !(this.isExcel2003(filePath) || this.isExcel2007(filePath))){
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }
    
    public static boolean isExcel2003(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    public static boolean isExcel2007(String filePath)  {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    public List<JobInfo> getJobExcelInfo(InputStream is,boolean isExcel2003){
        List<JobInfo> jobList=null;
        try{
            /** 根据版本选择创建Workbook的方式 */
            Workbook wb = null;
            //当excel是2003时
            if(isExcel2003){
                wb = new HSSFWorkbook(is);
            }
            else{//当excel是2007时
                wb = new XSSFWorkbook(is);
            }
            //读取Excel里面客户的信息
            jobList=readExcelValue(wb);
        }
        catch (IOException e)  {
            e.printStackTrace();
        }
        return jobList;
    }
    /**
     * 读取Excel里面任务调度信息
     * @param wb
     * @return
     */
    private List<JobInfo> readExcelValue(Workbook wb){
        //得到第一个shell
        Sheet sheet=wb.getSheetAt(0);

        //得到Excel的行数
        this.totalRows=sheet.getPhysicalNumberOfRows();

        //得到Excel的列数(前提是有行数)
        if(totalRows>=1 && sheet.getRow(0) != null){
            this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
        }

        List<JobInfo> jobInfoList=new ArrayList<JobInfo>();
        //循环Excel行数,从第二行开始。标题不入库
        for(int r=1;r<totalRows;r++){
            Row row = sheet.getRow(r);
            if (row == null) continue;
            
            JobInfo jobInfo=new JobInfo();
            //循环Excel的列
            for(int c = 0; c <this.totalCells; c++){
                Cell cell = row.getCell(c);
                if (null != cell){
                    if(c==0){
                        jobInfo.setJobGroup((int) cell.getNumericCellValue());
                    }else if(c==1){
                        jobInfo.setJobCron(cell.getStringCellValue());
                    }else if(c==2){
                        jobInfo.setJobDesc(cell.getStringCellValue());
                    }else if(c==3){
                        jobInfo.setExecutorRouteStrategy(cell.getStringCellValue());
                    }else if(c==4){
                        jobInfo.setExecutorHandler(cell.getStringCellValue());
                    }else if(c==5){
                        jobInfo.setExecutorBlockStrategy(cell.getStringCellValue());
                    }else if(c==6){
                        jobInfo.setExecutorFailStrategy(cell.getStringCellValue());
                    }
            }            
            }
          //添加任务列表
            jobInfoList.add(jobInfo);
       }
       return jobInfoList;
    }

}

Java:文件的上传服务

    @RequestMapping("batchAdd.do")
    @ResponseBody
    public AjaxResult batchAdd(@RequestParam("jobFile") MultipartFile jobFile, HttpServletRequest request,
            HttpServletResponse response) throws IOException{
        
        //判断文件是否为空
        if (jobFile==null) return null;
        //获取文件名
        String name=jobFile.getOriginalFilename();
        //进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)
        long size =jobFile.getSize();
        if (name==null ||("").equals(name) && size==0) return null;
        
        ExcelHelper readExcel=new ExcelHelper();
        //解析excel,获取任务调度集合。
        List<JobInfo> jobInfoList = readExcel.getJobExcelInfo(jobFile.getInputStream(),true);

        try {
            if(CollectionUtils.isNotEmpty(jobInfoList)){
                //迭代添加任务
                for(JobInfo _job:jobInfoList){
                    jobService.add(_job);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return AjaxResult.SUCCESS;
    }

 

posted @ 2018-06-13 10:52  shawWey  阅读(505)  评论(0编辑  收藏  举报