URL 下载图片

1、

import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.net.MalformedURLException;
import java.net.URL;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public ResponseEntity<ByteArrayResource> qrDownload() {
        String url = "图片地址"; //oss
        //下载  下载图片
        // 创建URL对象
        URL url = null;
        try {
            url = new URL(qrUnlimitCodes.getImg());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // 从URL读取图像
        BufferedImage image = null;
        try {
            image = ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 将图像转换为字节数组
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] imageBytes = baos.toByteArray();
        String fileName = "";
        // 创建响应实体,设置内容类型为图像
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(fileName).build());
        ByteArrayResource resource = new ByteArrayResource(imageBytes);

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(imageBytes.length)
                .body(resource);
    }

2、

public void qrDownload() {
        String url = "图片地址";  //oss
        //下载  下载图片
        // 设置 Content-Disposition 响应头
        try {
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(uuid, "UTF-8"));
            // 将用户重定向到另存为链接
            response.sendRedirect(url);
        } catch (OSSException | IOException e) {
            System.out.println("Error downloading object " + uuid + ": " + e.getMessage());
        }
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值