下载图片到指定目录

1、调用方式

String fileName = "http://localhost:9000/path/29002778.jpg";
String downloadUrl = "http:127.0.0.1:8080/common/download/pic?fileName=" + fileName;

2、下载方法

@GetMapping("/common/download/pic")
public void fileDownload(String fileName)  {
    String originalString = fileName.substring(fileName.lastIndexOf('/') + 1);//取出文件名29002778.jpg
    HttpURLConnection conn = null;
    InputStream inputStream = null;
    BufferedInputStream bis = null;
    FileOutputStream out = null;
    try
    {
        File file0=new File("D:\\path");
        if(!file0.isDirectory()&&!file0.exists()){
            file0.mkdirs();
        }
        out = new FileOutputStream(file0 + "\\" + originalString);
        // 建立链接
        //URL httpUrl=new URL("http://localhost:9000/path/29002778.jpg");//测试数据
        URL httpUrl = new URL(fileName);
        conn=(HttpURLConnection) httpUrl.openConnection();
        //以Post方式提交表单,默认get方式
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        // post方式不能使用缓存
        conn.setUseCaches(false);
        //连接指定的资源
        conn.connect();
        //获取网络输入流
        inputStream=conn.getInputStream();
        bis = new BufferedInputStream(inputStream);
        byte b [] = new byte[1024];
        int len = 0;
        while((len=bis.read(b))!=-1){
            out.write(b, 0, len);
        }
        System.out.println("下载完成...");
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        try {
            if(out!=null){
                out.close();
            }
            if(bis!=null){
                bis.close();
            }
            if(inputStream!=null){
                inputStream.close();
            }
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值