java Web 单文件下载与打包zip文件下载

1. 单文件下载

    @GetMapping("/showFile")
    
    @ApiOperation("预览文件")
    public void showFile(String path, HttpServletResponse response){
        File file = new File(path);
        if(!file.exists()){
            throw  new  RuntimeException("文件不存在");
        }
        try(FileInputStream fis = new FileInputStream(file)){
            ServletOutputStream os = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(file.getName(), "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");
            //每次写出1Mb
            byte[] data = new byte[1 << 30];
            int len = 0;
            //6.通过response对象获取OutputStream流
            //7.将FileInputStream流写入到buffer缓冲区
            while ((len = fis.read(data)) > 0) {
                //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                os.write(data, 0, len);
            }
        }catch (Throwable e){
            e.printStackTrace();
            throw  new  RuntimeException("查询文件失败");
        }
    }

2.多文件打包下载

代码中使用的 HttpRequest 工具类使用的是 hutool的工具包,使用前请先引用

<dependency>
     <groupId>cn.hutool</groupId>
     <artifactId>hutool-all</artifactId>
     <version>5.1.0</version>
</dependency>
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import cn.hutool.http.HttpRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public void downloadAttachments(Integer id, HttpServletRequest request, HttpServletResponse response) throws IOException {
   
   	response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("附件.zip", "UTF-8"));
   	response.setHeader("Connection", "close");
   	response.setHeader("Content-Type", "application/octet-stream");
   	
   	List<String> fileUrls = new ArrayList<>();
   	fileUrls.add("http://xxx.com/file/1.jpg");
   	try(ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())){
   		for (String fileUrl : fileUrls) {
   			InputStream inputStream = HttpRequest.get(fileUrl)
   					.execute()
   					.bodyStream();
   			String fileName = fileUrl.substring(fileUrl.lastIndexOf(File.separator) + 1);
   			zos.putNextEntry(new ZipEntry(fileName));
   			int len;
   			// 读入需要下载的文件的内容,打包到zip文件
   			byte[] buffer = new byte[1 << 30];
   			while ((len = inputStream.read(buffer)) > 0) {
   				zos.write(buffer, 0, len);
   			}
   			zos.closeEntry();
   			inputStream.close();
       }
   }catch(Exception e){
       e.printStackTrace();
   }		
   	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Quarkus 的 RESTful API 创建一个端点,该端点将接受图片的 URL,并使用 Java ImageIO 库将其下载到本地,然后将所有下载的图片打包ZIP 文件并下载到客户端。以下是一个简的示例代码: ```java import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.imageio.ImageIO; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Response; import org.jboss.resteasy.annotations.jaxrs.QueryParam; @Path("/images") public class ImageResource { @GET @Path("/download") @Produces("application/zip") public Response downloadImagesAsZip(@QueryParam("urls") List<String> urls) throws IOException { // Create a ByteArrayOutputStream to store the ZIP file content ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Create a ZipOutputStream to write the ZIP file content ZipOutputStream zos = new ZipOutputStream(baos); // Create a list to store all the downloaded images List<BufferedImage> images = new ArrayList<>(); // Download all the images and add them to the list for (String url : urls) { BufferedImage image = ImageIO.read(new URL(url)); images.add(image); } // Write all the images to the ZIP file for (int i = 0; i < images.size(); i++) { BufferedImage image = images.get(i); // Create a new ZIP entry with the image name ZipEntry entry = new ZipEntry("image_" + i + ".png"); zos.putNextEntry(entry); // Write the image content to the ZIP file ImageIO.write(image, "png", zos); zos.closeEntry(); } // Close the ZipOutputStream zos.close(); // Convert the ByteArrayOutputStream to a byte array byte[] data = baos.toByteArray(); // Create a Response object with the ZIP file content Response.ResponseBuilder response = Response.ok(data); // Set the content-disposition header to force the download of the ZIP file response.header("Content-Disposition", "attachment; filename=images.zip"); // Return the Response object return response.build(); } } ``` 这个示例代码创建了一个名为 `/images/download` 的端点,它接受一个名为 `urls` 的查询参数,该参数是一个 URL 列表,代表要下载的图片的 URL。该端点会下载所有的图片,并将它们打包成一个名为 `images.zip` 的 ZIP 文件,然后将 ZIP 文件作为响应体发送给客户端。客户端会自动下载 ZIP 文件。 你可以使用类似于以下的 curl 命令来测试该端点: ``` curl -o images.zip "http://localhost:8080/images/download?urls=http://example.com/image1.png&urls=http://example.com/image2.png" ``` 该命令会从 `http://example.com/image1.png` 和 `http://example.com/image2.png` 下载两张图片,并将它们打包成一个名为 `images.zip` 的 ZIP 文件,然后将 ZIP 文件保存在当前目录下。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值