java批量下载world文档

java批量下载world文档直接上代码 批量下载文件 param request param response return RequestMappi downloadAttr public void downloadAttr HttpServletR request

大家好,我是讯享网,很高兴认识大家。

直接上代码:

         /
     * 批量下载文件 
     * @param request
     * @param response
     * @return
     */
      @RequestMapping("/downloadAttr")
  public void downloadAttr(HttpServletRequest request, HttpServletResponse response) {  
    ExportToWorldUtil worldUtil = new ExportToWorldUtil(); 
    String serverPath = "D:\\tempWorld";        //首先创建一个服务器压缩文件路径
        List<File> srcfile = new ArrayList<File>();  //声明一个集合,用来存放多个world文件路径及名称

        String userId = request.getParameter("userId"); 
        String [] userIds =userId.split(",");
        try {  
            for(int i=0;i<userIds.length;i++){
        if(userIds[i]!=null && !"".equals(userIds[i])){
        Accessory accessory = new Accessory(); 
                     accessory.setUserId(userIds[i]);
                     List<Accessory> listAttach = accessoryService.findByUser(accessory); //数据库查询数据
                    if(listAttach!=null && listAttach.size()>0){
                   Accessory acc = listAttach.get(0);
                  srcfile.add(new File(acc.getPath()));              
                     }else{
                  continue;
                     }
        }
        }
            if(listAttach.size()>0){
            worldUtil.exportWorld( srcfile, serverPath, response, request);  
            }
            
        } catch (Exception e1) {  
            e1.printStackTrace();  
        } 

    }  


讯享网

ExportToWorldUtil类:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import com.ibm.icu.text.SimpleDateFormat;


public class ExportToWorldUtil {
   
     public void exportWorld( List<File> srcfile ,String serverPath, HttpServletResponse response,HttpServletRequest request) throws Exception{     
          
         File zip = new File(serverPath+".zip");
              ZipFiles(srcfile, zip);  
              //下载
              downFile(response, serverPath, ".zip");  //实现将压缩包写入流中,下载到本地,并删除临时文件中的压缩包及文件
     }     
 
    //压缩文件  
    public static void ZipFiles(List<File> srcfile, java.io.File zipfile) {  
        byte[] buf = new byte[1024];  
        try {  
                ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));  
             
                for (int i = 0; i < srcfile.size(); i++) {    
                    File file = srcfile.get(i);    
                    FileInputStream in = new FileInputStream(file);    
                    // Add ZIP entry to output stream.    
                    out.putNextEntry(new ZipEntry(file.getName()));    
                    // Transfer bytes from the file to the ZIP file    
                    int len;    
                    while ((len = in.read(buf)) > 0) {    
                        out.write(buf, 0, len);    
                    }    
                    // Complete the entry    
                    out.closeEntry();    
                    in.close();    
                }    
                            
            out.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }        
    
    public static void downFile(HttpServletResponse response,String serverPath, String str) {    
        //下面注释代码虽然少,但是慎用,如果使用,压缩包能下载,但是下载之后临时文件夹会被锁住被jvm占用,不能删除
//        response.setCharacterEncoding("utf-8");  
//         try {
//             File file=new File(serverPath,str);
//             response.setHeader("Content-Disposition",
//                        "attachment; filename="+ StringUtil.encodingFileName(str));
//                response.setContentType("application/octet-stream; charset=utf-8");
//                InputStream in1 =new FileInputStream(file.getPath());
//                IOUtils.copy(in1, response.getOutputStream());
//       
//          } 
//          catch (IOException ex) {
//             ex.printStackTrace();
//         }
        
        
        try {    
            String path = serverPath + str;    
            File file = new File(path);    
            if (file.exists()) {    
                InputStream ins = new FileInputStream(path);    
                BufferedInputStream bins = new BufferedInputStream(ins);// 放到缓冲流里面    
                OutputStream outs = response.getOutputStream();// 获取文件输出IO流    
                BufferedOutputStream bouts = new BufferedOutputStream(outs);   
                response.setContentType("application/ostet-stream");// 设置response内容的类型    
                response.setHeader(    
                        "Content-disposition",    
                        "attachment;filename="    
                                + URLEncoder.encode("个人简历"+str, "UTF-8"));// 设置头部信息    
                int bytesRead = 0;    
                byte[] buffer = new byte[8192];    
                 //开始向网络传输文件流    
                while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {    
                   bouts.write(buffer, 0, bytesRead);    
               }    
                bouts.flush();// 这里一定要调用flush()方法    
                ins.close();    
                bins.close();    
                outs.close();    
                bouts.close();    
            } else {    
                response.sendRedirect("../error.jsp");    
            }    
        } catch (IOException e) {    
            e.printStackTrace();  
        }finally{
            File file1=new File(serverPath);
            deleteExcelPath(file1);  //删除临时目录
        }    
    }  
    /  
     * 删除目录下所有的文件;  
     * @param path  
     */    
    public static boolean deleteExcelPath(File file){    
        String[] files = null;    
        if(file != null){    
            files = file.list();    
        }    
        if(file.isDirectory()){    
            for(int i =0;i<files.length;i++){    
                boolean bol = deleteExcelPath(new File(file,files[i]));    
                if(bol){    
                    System.out.println("删除成功!");    
                }else{    
                    System.out.println("删除失败!");    
                }    
            }    
        }    
        return file.delete();    
    }   


   
    
 }    

    
小讯
上一篇 2025-04-04 19:13
下一篇 2025-02-27 15:42

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/122589.html