Java file download function code (single file download, multi-file batch package download) - universally applicable

1. Preface
  When programmers are working on web projects, they often need to add the functions of uploading, downloading, and deleting files. Sometimes it is a single file, sometimes a batch operation of multiple files, and the code programmers of these functions can collect them as tools. Use, in this way, programmers will get twice the result with half the effort when programming, then the next blog will introduce the use of the file upload and download functions of each framework.
  The focus of this blog is on the file download function code that can be applied to each framework. Without further ado, let’s cut directly to the topic:

2. Examples

  1. The jar packages that generally need to be added:
   commons.fileupload-1.2.1.jar and commons.io-1.4.0.jar, click to download the jar package
   2. Method example:


//普通java文件下载方法,适用于所有框架  
public void downloadFile() throws IOException{  

    //获取文件根目录,不同框架获取的方式不一样,可自由切换  
    String basePath = request.getSession().getServletContext().getRealPath("/upload/text");  

    //获取文件名称(包括文件格式)  
    String fileName = request.getParameter("downFileName");  

    //组合成完整的文件路径  
    String targetPath = basePath+File.separator+fileName;  

    //模拟多一个文件,用于测试多文件批量下载  
    String targetPath1 = basePath+File.separator+"ggg.jpg";  
    System.out.println("文件名:"+fileName);  
    System.out.println("文件路径:"+targetPath);  

    //方法1:IO流实现下载的功能  
    HttpServletResponse res = getResponse(); //创建response回应  
    res.setContentType("text/html; charset=UTF-8"); //设置编码字符  
    res.setContentType("application/x-msdownload"); //设置内容类型为下载类型  
    res.setHeader("Content-disposition", "attachment;filename="+fileName);//设置下载的文件名称  
    OutputStream out = res.getOutputStream();   //创建页面返回方式为输出流,会自动弹出下载框   

/*  //方法1-1:IO字节流下载,用于小文件  
    System.out.println("字节流下载");  
    InputStream is = new FileInputStream(targetPath);  //创建文件输入流  
    byte[] Buffer = new byte[2048];  //设置每次读取数据大小,即缓存大小  
    int size = 0;  //用于计算缓存数据是否已经读取完毕,如果数据已经读取完了,则会返回-1  
    while((size=is.read(Buffer)) != -1){  //循环读取数据,如果数据读取完毕则返回-1  
        out.write(Buffer, 0, size); //将每次读取到的数据写入客户端  
    }  
*/    

/*  //方法1-2:IO字符流下载,用于大文件  
    System.out.println("字符流");  
    File file = new File(targetPath);  //创建文件  
    FileInputStream fis=new FileInputStream(targetPath);  //创建文件字节输入流  
    BufferedInputStream buff=new BufferedInputStream(fis); //创建文件缓冲输入流  
    byte [] b=new byte[2048];  //设置每次读取大小  
    long l=0;  //用于判断是否等同于文件的长度,即文件下载大小  
    while(l<file.length()){  //循环读取文件  
        int j=buff.read(b,0,2048); //使用缓冲流读取数据,返回缓冲区长度  
        l+=j;  
        out.write(b,0,j);//将缓存写入客户端  
    }  
*/   

/*  //方法1-3:将附件中多个文件进行压缩,批量打包下载文件  
    //创建压缩文件需要的空的zip包  
    String zipBasePath=request.getSession().getServletContext().getRealPath("/upload/zip/");  
    String zipFilePath = zipBasePath+"temp.zip";  

    //创建文件路径的集合,  
    List<String> filePath = new ArrayList<String>();  
    filePath.add(targetPath);  
    filePath.add(targetPath1);  

    //根据临时的zip压缩包路径,创建zip文件  
    File zip = new File(zipFilePath);  
    if (!zip.exists()){     
        zip.createNewFile();     
    }  

    //创建zip文件输出流  
    FileOutputStream fos = new FileOutputStream(zip);  
    ZipOutputStream zos = new ZipOutputStream(fos);  

    //循环读取文件路径集合,获取每一个文件的路径  
    for(String fp : filePath){  
        File f = new File(fp);  //根据文件路径创建文件  
        zipFile(f, zos);  //将每一个文件写入zip文件包内,即进行打包  
    }  
    fos.close();  
    zos.close();  

    //将打包后的文件写到客户端,输出的方法同上,使用缓冲流输出  
    InputStream fis = new BufferedInputStream(new FileInputStream(zipFilePath));  
    byte[] buff = new byte[4096];  
    int size = 0;  
    while((size=fis.read(buff)) != -1){  
        out.write(buff, 0, size);  
    }  

*/  
    //释放和关闭输入输出流  
    //out.flush();  
    //out.close();  
    //fis.close();  
    //buff.close();  
    //is.close();  
}  

//封装压缩文件的方法  
public  void zipFile(File inputFile,ZipOutputStream zipoutputStream) {  
        try {  
            if(inputFile.exists()) { //判断文件是否存在  
                if (inputFile.isFile()) {  //判断是否属于文件,还是文件夹  

                    //创建输入流读取文件  
                    FileInputStream fis = new FileInputStream(inputFile);  
                    BufferedInputStream bis = new BufferedInputStream(fis);  

                    //将文件写入zip内,即将文件进行打包  
                    ZipEntry ze = new ZipEntry(inputFile.getName()); //获取文件名  
                    zipoutputStream.putNextEntry(ze);     

                    //写入文件的方法,同上                  
                    byte [] b=new byte[1024];  
                long l=0;  
                while(l<inputFile.length()){  
                    int j=bis.read(b,0,1024);  
                    l+=j;  
                    zipoutputStream.write(b,0,j);  
                }  
                    //关闭输入输出流  
                    bis.close();  
                    fis.close();  
                } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip  
                    try {  
                        File[] files = inputFile.listFiles();  
                        for (int i = 0; i < files.length; i++) {  
                            zipFile(files[i], zipoutputStream);  
                        }  
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
}  

3. Summary

  1. This method combines byte stream and character stream for single file and multi-file package download. Method 1-1, method 1-2 and method 1-3 belong to different forms of download methods, all of which are based on method 1. For the above operations , the three methods cannot be used at the same time, and which type of method needs to be used, just remove the comment;   2. Practice is the only criterion for testing the truth of cognition. will understand why



Previous: The problem of "404 not found" caused by adding the folder name to the absolute path and action request path
of jfinal Next: The function code for downloading the springmvc file of the ssh framework


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325278866&siteId=291194637