JAVA中批量下载文件,将下载多个文件打包成zip文件下载。

 /**   * 文件下载
* @param request
* @param response
* @param filePath 文件路径
* @param filename 下载时文件名称
*/
    public static void downLoadFile(HttpServletRequest request,HttpServletResponse response,String filePath,String filename){
        try {
            File file=new File(filePath);
// 先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,这个文件名称 用于浏览器的下载框中自动显示的文件名
            String userAgent =request.getHeader("User-Agent");
            if(userAgent.contains("MSIE")||userAgent.contains("Trident")){
                filename= java.net.URLEncoder.encode(filename,"UTF-8");
            }else{
                filename=new String(filename.getBytes("utf-8"),"iso8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" +filename );
//response.setContentType("application/vnd.ms-excel");
            response.setContentType("mu
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用`java.util.zip`来实现根据URL将多个文件打包zip并进行下载的功能。下面是一个示例代码: ```java import java.io.*; import java.net.URL; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileZipDownloader { public static void main(String[] args) { String zipUrl = "http://example.com/files.zip"; String[] fileUrls = {"http://example.com/file1.txt", "http://example.com/file2.txt"}; try { // 创建ZipOutputStream FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 从URL下载并添加文件zip for (String fileUrl : fileUrls) { URL url = new URL(fileUrl); InputStream is = url.openStream(); zos.putNextEntry(new ZipEntry(url.getFile())); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { zos.write(buffer, 0, length); } is.close(); zos.closeEntry(); } // 关闭流 zos.close(); fos.close(); // 下载zip文件 downloadZip(zipUrl); } catch (IOException e) { e.printStackTrace(); } } private static void downloadZip(String url) throws IOException { URL zipUrl = new URL(url); InputStream is = zipUrl.openStream(); FileOutputStream fos = new FileOutputStream("downloaded_files.zip"); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } is.close(); fos.close(); } } ``` 上述代码首先创建了一个`ZipOutputStream`对象,然后依次遍历多个文件的URL,将每个文件下载后添加到zip,并关闭流。最后调用`downloadZip`方法根据zip文件的URL进行下载。请确保提供的URL和文件格式的可用性和正确性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值