上传和下载文件

1. 上传文件

(1) controller

@RequestMapping(value={"/uploadFile"},method={RequestMethod.POST}) 
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam Integer groupId,HttpServletRequest request) {  
        String result="";        
        try{         
            POIFSFileSystem fs;      //上传的文件为excel   
            HSSFWorkbook book;
            fs = new POIFSFileSystem(file.getInputStream());  
            book = new HSSFWorkbook(fs);        
           //  获得第一个工作表对象 
           HSSFSheet sheet = book.getSheetAt(0);
         
           //插入数据的代码
           String sql;
           sql="insert into question (test,question_option,answer,question_group)values(?,?,?,?)";
          
           List<HashMap<String,Object>> data=new ArrayList<HashMap<String,Object>>();
           HashMap<String,Object> one=null;
           // 得到总行数        
           int rowNum = sheet.getLastRowNum();        
          HSSFRow row = sheet.getRow(0);        
           // 正文内容应该从第二行开始,第一行为表头的标题       
         for (int i = 1; i <= rowNum; i++) {           
               row = sheet.getRow(i);  
               HSSFCell cell=row.getCell((short)0);   //题目
               HSSFCell cell2=row.getCell((short)1);   //答案
               HSSFCell cell3=row.getCell((short)2);   //选项
            if(cell==null||cell2==null||cell3==null){
                   result="1";                    
               }else{
                   one=new HashMap<String,Object>();
                   one.put("title", cell.getStringCellValue());
                   one.put("answer", cell2.getStringCellValue());
                   one.put("option", cell3.getStringCellValue());
                   one.put("group", groupId);
                   data.add(one);
               }   
           }
         if(this.springDBAction.insertBatch(sql, data, new Object[]{"title","option","answer","group"})>0){   //批量插入
             result="2";
         }else{
             result="1";
         }
    
     }catch (Exception e){
           e.printStackTrace();
           result="1";
        }
       request.setAttribute("result", result);
       request.setAttribute("groupId", groupId);
        return "/questionManager/questionList";  
    }

注意:
其中multipartFile 类它有一个方法可以将该对象指定的文件复制到另一个文件中:file.transferTo(File file).这样可以将上传的文件复制到别的目录下的文件中。

(2) jsp页面

 <div id="upload" class="upload" style="display:none;"> 
   <div><img src="<%=path%>/images/close.png" style="border:0;cursor:pointer;"></div>
   <form name="uploadFile" method="post" action="<%=path%>/question/uploadFile" enctype="multipart/form-data">
   <ul class="forminfo uploadUl">
     <li>
        <label>选择文件:</label>
        <input type="file" name="file" id="file"></li>
     <li><input type="hidden" name="groupId"></li>
     <li><center><input type="button" value="提交" onclick="checkSubmit();" class="addbtn" style="float:none;"></center></li>
   </ul>
   </form>
 </div> 

(3) jsp页面上的checkSubmit方法(javascript)

 var checkSubmit=function(){
      if(document.getElementById("file").value!=undefined&&document.getElementById("file").value!=""){
        document.forms[0].submit();
      }else{
        alert("请选择文件");
      }      
    };

2. 下载文件(这里以下载html文件为例)

 首先构成html代码,接着将html转换成word文件,将几个word文件打包成zip进行下载。

(1)controller

    @RequestMapping("/download")
    public String download(HttpServletRequest request,HttpServletResponse response)throws Exception{
        response.setContentType("text/html;charset=utf-8");    //设置回应流的头文件
        request.setCharacterEncoding("UTF-8");
        
        int paperId=Integer.valueOf(request.getParameter("paperId"));
        int groupId=Integer.valueOf(request.getParameter("groupId"));
        
        BufferedInputStream bis= null;
        BufferedOutputStream bos=null;
        String ctxPath =request.getSession().getServletContext().getRealPath("/")+"\\"+"exam\\";   //获得根目录下的exam文件夹地址
        if(!new File(ctxPath).exists()){
            new File(ctxPath).mkdirs();
        }
        
        String sql="select top(1) exam_name as name,question_ids as questionIds from paper where id=?";
        List<HashMap<String,Object>> data=this.springDBAction.query(sql,new Object[]{paperId});
        if(data.size()!=0){     //根据数据构成html字符串
            String fileName=data.get(0).get("name").toString();
            String content="<html><div style=\"width: 96%;padding:10px;font-family: \'微软雅黑\';\"><div>"
                          +"<center><h3 style=\"margin: 0;\">"+fileName+"</h3></center></div><hr style=\"height:1px;color:#000000;\"/><div >"
                          +"<ul style=\"display: block;margin: 0;list-style: none;font-size:15pt;border: 0;\">";
            String answers="<html><div><ul style=\"display: block;margin: 0;list-style: none;font-size:15pt;border: 0;\">";
            
            String[] questionStr=data.get(0).get("questionIds").toString().split(",");
            sql="select test as title, answer as answer,question_option as questionOption from question where id in(";            
            for(int i=0;i<questionStr.length;i++){
                sql+=Integer.valueOf(questionStr[i])+",";
            }
            sql=sql.substring(0,sql.lastIndexOf(","));
            sql+=")";
            data=this.springDBAction.query(sql, new Object[0]);
            HashMap<String,Object> one;
            for(int i=0;i<data.size();i++){
                one=data.get(i);
                content+="<li style=\"margin-bottom: 13px;clear: both;display: block;margin: 0;padding: 0;list-style: none;\"><label style=\"font-size:15pt;\">"+(i+1)+".  "+one.get("title")+"</label>"
                    +"<ul style=\"display: block;margin: 0;list-style: none;font-size: 10pt;border: 0;padding: 10 0 10 30;\">";
                answers+="<li style=\"margin-bottom: 13px;clear: both;display: block;margin: 0;padding: 0;list-style: none;\"><label style=\"font-size:15pt;\">"+(i+1)+".  "+one.get("answer")+"</label>"
                +"</li>";
                
                String[] strs=one.get("questionOption").toString().split(";");
                for(String str:strs){
                    if(str.trim().startsWith("A.")){
                        content+="<li style=\"margin-bottom: 13px;clear: both; display:inline;padding-right:70px;list-style: none;margin:0;\"><label style=\"font-size:13px;\">A.</label>"
                                +"<label style=\"font-size:13pt;\">"+str.trim().substring(2)+"</label></li>";
                    }
                }
                for(String str:strs){
                    if(str.trim().startsWith("B.")){
                        content+="<li style=\"margin-bottom: 13px;clear: both; display:inline;padding-right:70px;list-style: none;margin:0;\"><label style=\"font-size:13px;\">B.</label>"
                                +"<label style=\"font-size:13pt;\">"+str.trim().substring(2)+"</label></li>";
                    }
                }
                for(String str:strs){
                    if(str.trim().startsWith("C.")){
                        content+="<li style=\"margin-bottom: 13px;clear: both; display:inline;padding-right:70px;list-style: none;margin:0;\"><label style=\"font-size:13px;\">C.</label>"
                                +"<label style=\"font-size:13pt;\">"+str.trim().substring(2)+"</label></li>";
                    }
                }
                for(String str:strs){
                    if(str.trim().startsWith("D.")){
                        content+="<li style=\"margin-bottom: 13px;clear: both; display:inline;padding-right:70px;list-style: none;margin:0;\"><label style=\"font-size:13px;\">D.</label>"
                                +"<label style=\"font-size:13pt;\">"+str.trim().substring(2)+"</label></li>";
                    }
                }
                content+="</ul></li>";
            }
            content+="</ul></div></div></html>";
            answers+="</ul></div></html>";
            
            String downLoadPath=ctxPath+fileName+".doc";
            String answerPath=ctxPath+fileName+"_答案.doc";
            
            ByteArrayInputStream bais = new ByteArrayInputStream(content.getBytes());    //生成第一个word文档
            POIFSFileSystem poifs = new POIFSFileSystem();  
            DirectoryEntry directory = poifs.getRoot();  
            DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);  
            FileOutputStream ostream = new FileOutputStream(downLoadPath);  
            poifs.writeFilesystem(ostream);  
            bais.close();  
            ostream.close();  
            
            bais = new ByteArrayInputStream(answers.getBytes());     //生成第二个word文档
            poifs = new POIFSFileSystem();  
            directory = poifs.getRoot();  
            documentEntry = directory.createDocument("WordDocument", bais);  
            ostream = new FileOutputStream(answerPath);  
            poifs.writeFilesystem(ostream);  
            bais.close();  
            ostream.close(); 
            
            try{
                long fileLength = new File (downLoadPath).length()+new File (answerPath).length();    //补充response的head
                response.setContentType("application/octet-stream; charset=utf-8");   //表示可以下载任何类型的文件
                response.setHeader("Content-disposition","attachment;filename="+new String((fileName+".zip").getBytes("utf-8"),"ISO8859-1"));               //防止中文乱码
                response.setHeader("Content-Length",String.valueOf(fileLength));
                
                 ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());       //构成zip流
                 File[] subs = new File[2];  
                 subs[0]=new File(downLoadPath);  
                 subs[1]=new File(answerPath);      
                     
                for (int i=0;i<subs.length;i++) {  
                       File f=subs[i];  
                       zos.putNextEntry(new ZipEntry(f.getName()));     
                       FileInputStream fis = new FileInputStream(f);     
                       byte[] buffer = new byte[1024];     
                       int r = 0;     
                       while ((r = fis.read(buffer)) != -1) {     
                           zos.write(buffer, 0, r);     
                       }     
                       fis.close();   
                }  
                zos.flush();     
                zos.close(); 

//下载单个文件
// bis = new BufferedInputStream(new FileInputStream(downLoadPath)); // bos = new BufferedOutputStream(response.getOutputStream()); // byte[] buff = new byte[2048]; // int bytesRead; // while (-1!=(bytesRead=bis.read(buff,0,buff.length))){ // bos.write(buff,0,bytesRead); // } } catch(Exception e){ e.printStackTrace(); }finally{ if(bis!=null) bis.close(); if (bos!=null) bos.close(); } return null; }else{ request.setAttribute("groupId", groupId); return "/paperManager/paperList"; } }

 

posted @ 2014-08-04 18:32  夏之夜  阅读(282)  评论(0编辑  收藏  举报