网络图片下载-Java精品记录

原文引用自: https://www.jianshu.com/p/2f7a4d1f149a

精品

web-servlet: 也就是controller

@Controller
@RequestMapping("/admin/source/product_batch")
public class ProductBatchController {
      /**
     * 溯源二维码图片下载
     * */
    @GetMapping("{id}/down")
    public void imageDown(@PathVariable Long id, HttpServletResponse response){
        //这里查询出来的是图片的链接,替换成你自己的
        ProductBatchDTO productBatchDTO = productBatchService.findById(id);
        //链接地址
        String filePath = productBatchDTO.getSourceQrCode();

        String realName = "product_source_batch_qr_code"+productBatchDTO.getProductId()+"_"+productBatchDTO.getBatchNumber()+".jpg";
        // 设置响应头,控制浏览器下载该文件
        response.reset();
        response.setStatus(HttpServletResponse.SC_OK);
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realName, "UTF-8"));
            ImagesUtil.download(response,filePath, realName);
        } catch (Exception e) {
            ServletOutputStream sos = null;
            try {
                response.setContentType("text/html;charset=utf-8");
                sos = response.getOutputStream();
                sos.write("<script>alert('下载失败,请与管理员联系~~');</script>".getBytes(""utf-8""));
                sos.flush();
            } catch (IOException e1) {
                log.error("下载溯源二维码图片报错:{}",e.getMessage());
            }finally{
                if(null != sos){
                    try {
                        sos.close();
                    } catch (IOException e1) {
                        log.error("下载溯源二维码图片报错:{}",e1.getMessage());
                    }
                }
            }
        }
    }
}

工具类:

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
 
import javax.servlet.http.HttpServletResponse;
 
/**
 *图片下载的公共方法
 * @author rp
 */
public class ImagesUtil {
    public static void download2(HttpServletResponse response,String urlString, String filename) throws Exception {
        //new一个URL对象  
        URL url = new URL(urlString);  
        //打开链接  
        URLConnection conn = url.openConnection();  
         
        //超时响应时间为5秒  
        conn.setConnectTimeout(5 * 1000);  
        //通过输入流获取图片数据  
        InputStream inStream = conn.getInputStream();  
        //得到图片的二进制数据,以二进制封装得到数据,具有通用性  
        byte[] data = readInputStream(inStream);  
        //new一个文件对象用来保存图片,默认保存当前工程根目录  
        //File imageFile = new File(filename);  
        //创建输出流  
        OutputStream outStream = response.getOutputStream();
        //写入数据  
        outStream.write(data);  
        //关闭输出流  
        outStream.close();  
    }
    
    public static void download(HttpServletResponse response,String urlString, String filename) throws Exception {
        // 构造URL
        URL url = new URL(urlString);
        // 打开连接
        URLConnection con = url.openConnection();
     
        //超时响应时间为10秒  
        con.setConnectTimeout(10 * 1000);  
        // 输入流
        InputStream is = con.getInputStream();
        // 1K的数据缓冲
        byte[] bs = new byte[1024];
        // 读取到的数据长度
        int len;
        // 输出的文件流
        OutputStream os =response.getOutputStream();
        // 开始读取
        while ((len = is.read(bs)) != -1) {
          os.write(bs, 0, len);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
    }  
    
    public static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        //创建一个Buffer字符串  
        byte[] buffer = new byte[1024];  
        //每次读取的字符串长度,如果为-1,代表全部读取完毕  
        int len = 0;  
        //使用一个输入流从buffer里把数据读取出来  
        while( (len=inStream.read(buffer)) != -1 ){  
            //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度  
            outStream.write(buffer, 0, len);  
        }  
        //关闭输入流  
        inStream.close();  
        //把outStream里的数据写入内存  
        return outStream.toByteArray();  
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值