Java Springboot如何基于图片生成下载链接

 更新时间:2020年03月30日 10:20:41   作者:NemoWang  
这篇文章主要介绍了Java Springboot如何基于图片生成下载链接,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

现有一些图片在服务器上的链接,在浏览器中打开这些链接是直接显示在浏览器页面的形式。

现在需要生成这些图片的单独下载以及打包下载链接,即在浏览器中打开下载链接后弹出下载框提示下载。由于前端存在跨域问题,所以图片下载由后台接口完成。

首先编写文件下载工具类:

import java.net.URL;
import java.net.MalformedURLException;
import org.apache.commons.io.FileUtils;

public class FileDownloadUtil {
/**
   * 下载文件---返回下载后的文件存储路径
   *
   * @param url 文件路径
  * @param dir 目标存储目录
  * @param fileName 存储文件名
  * @return
  */
  public static void downloadHttpUrl(String url, String dir, String fileName) throws BusinessException {
    try {
    URL httpurl = new URL(url);
    File dirfile = new File(dir);
      if (!dirfile.exists()) {
        dirfile.mkdirs();
      }
      FileUtils.copyURLToFile(httpurl, new File(dir+fileName));
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();26     }
  }

  public static boolean deleteFile(File file) {
    if (file.exists()) {
      return file.delete();
    }
    return false;
  }
}

单张图片下载

Controller层接口:

import org.apache.commons.lang.StringUtils;
import java.io.*;


protected HttpServletResponse response;

/**
   * 单张图片下载
   *
   * @param url 要下载的图片url
   * @author: nemowang
   */
  @ApiImplicitParams({
      @ApiImplicitParam(name = "url", value = "图片url", required = true, dataType = "String", paramType = "query"),
  })
  @ApiOperation(value = "单张图片下载", notes = "单张图片下载")
  @RequestMapping(value = "/downloadPicture", method = RequestMethod.GET)
  public void downloadPicture(String url) {
    
    // 拼接完整图片路径。这里填写图片链接
    String urlPath = "";

    // 获取图片文件后缀名
    String postfix = "." + StringUtils.substringAfterLast(url, ".");

    // 获取当前类的所在项目路径
    File directory = new File("");
    String courseFile;

    String srcPath;
    File srcFile = null;
    FileInputStream fileInputStream = null;
    InputStream fis = null;
    OutputStream out = null;
    try {
      courseFile = directory.getCanonicalPath();
      String fileName = "\\" + StringUtil.getUUID() + postfix;
      // 下载文件
      FileDownloadUtil.downloadHttpUrl(urlPath, courseFile, fileName);

      srcPath = courseFile + fileName;
      srcFile = new File(srcPath);

      fileInputStream = new FileInputStream(srcPath);
      fis = new BufferedInputStream(fileInputStream);
      byte[] buffer = new byte[fis.available()];
      fis.read(buffer);

      response.setContentType("application/octet-stream");
      response.setHeader("Content-disposition", "attachment;filename=" + fileName);
      out = response.getOutputStream();
      out.write(buffer);
      out.flush();
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
        if (fis != null) {
          fis.close();
        }
        if (out != null) {
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // 删除中间文件
    if (srcFile != null) {
      System.out.println(FileDownloadUtil.deleteFile(srcFile));
    }
  }

因为是GET请求,所以直接拼接接口路由+参数,用浏览器打开就能弹出下载。

至此单张图片下载接口结束。

多张图片打包下载

Controller层接口:

/**
   * 图片打包下载
   */
  @ApiImplicitParams({
      @ApiImplicitParam(name = "urls", value = "图片url列表", required = true, dataType = "List", paramType = "query"),
  })
  @ApiOperation(value = "图片打包下载", notes = "图片打包下载")
  @RequestMapping(value = "/downloadPictureList", method = RequestMethod.GET)
  public void downloadPictureList(List urls) {
    List<String> fileNameList = new ArrayList<>();

    for (int i = 0; i < urls.size(); i++) {
      // 获取文件名
      fileNameList.add(StringUtils.substringAfterLast(urls.get(i), "/"));

      // 拼接完整图片路径
      urls.set(i, DOMAIN + urls.get(i));
    }

    // 获取当前类的所在项目路径
    File directory = new File("");
    String courseFile;

    String srcPath;
    File srcFile = null;

    // 要打包的文件列表
    List<File> fileList = new ArrayList<>();

    ZipOutputStream zos = null;
    OutputStream out = null;
    try {
      courseFile = directory.getCanonicalPath();

      // 下载文件
      for (int i = 0; i < urls.size(); i++) {
        String fileName = "\\" + fileNameList.get(i);
        FileDownloadUtil.downloadHttpUrl(urls.get(i), courseFile, fileName);
        srcPath = courseFile + fileName;
        srcFile = new File(srcPath);
        fileList.add(srcFile);
      }



      long start = System.currentTimeMillis();

      response.setContentType("application/x-zip-compressed");
      response.setHeader("Content-disposition", "attachment;filename=" + StringUtil.getUUID() + ".zip");
      out = response.getOutputStream();
      zos = new ZipOutputStream(out);
      for (File file : fileList) {
        byte[] buf = new byte[BUFFER_SIZE];
        zos.putNextEntry(new ZipEntry(file.getName()));
        int len;
        FileInputStream in = new FileInputStream(file);
        while ((len = in.read(buf)) != -1) {
          zos.write(buf, 0, len);
        }
        zos.closeEntry();
        in.close();
      }
      long end = System.currentTimeMillis();
      System.out.println("压缩完成,耗时:" + (end - start) + " ms");


      out.flush();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
        throw new RuntimeException("zip error from ZipUtils", e);
    } finally {
      if (zos != null) {
        try {
          zos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      if (out != null) {
        try {
          zos.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

    // 删除中间文件
    if (fileList != null) {
      for (File file : fileList) {
        System.out.println(FileDownloadUtil.deleteFile(file));
      }
    }
  }

同样是GET请求,所以也是拼接接口路由+参数,用浏览器打开就能弹出下载。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java如何生成登录随机验证码

    java如何生成登录随机验证码

    这篇文章主要为大家详细介绍了java如何生成登录随机验证码,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-12-12
  • ResponseBodyAdvice踩坑及解决

    ResponseBodyAdvice踩坑及解决

    这篇文章主要介绍了ResponseBodyAdvice踩坑及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • 详解ElasticSearch6.4.0集群搭建

    详解ElasticSearch6.4.0集群搭建

    这篇文章主要介绍了详解ElasticSearch6.4.0集群搭建,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-09-09
  • Spring MVC文件配置以及参数传递示例详解

    Spring MVC文件配置以及参数传递示例详解

    这篇文章主要给大家介绍了关于Spring MVC文件配置以及参数传递的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Mybatis返回插入主键id的方法

    Mybatis返回插入主键id的方法

    这篇文章主要介绍了 Mybatis返回插入主键id的方法,在文章底部给大家补充了Mybatis中insert中返回主键ID的方法,非常不错,需要的朋友可以参考下
    2017-04-04
  • Java多线程编程之ThreadLocal线程范围内的共享变量

    Java多线程编程之ThreadLocal线程范围内的共享变量

    这篇文章主要介绍了Java多线程编程之ThreadLocal线程范围内的共享变量,本文讲解了ThreadLocal的作用和目的、ThreadLocal的应用场景、ThreadLocal的使用实例等,需要的朋友可以参考下
    2015-05-05
  • Java 实现FTP服务实例详解

    Java 实现FTP服务实例详解

    这篇文章主要介绍了Java 实现FTP服务实例详解的相关资料,需要的朋友可以参考下
    2017-04-04
  • javaWeb传收参数方式总结示例分析

    javaWeb传收参数方式总结示例分析

    这篇文章主要为大家介绍了javaWeb传收参数方式总结示例分析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-08-08
  • Java 使用getClass().getResourceAsStream()方法获取资源

    Java 使用getClass().getResourceAsStream()方法获取资源

    这篇文章主要介绍了Java 使用getClass().getResourceAsStream()方法获取资源的相关资料,这里主要讲解哪种方式可以获取到文件资源,需要的朋友可以参考下
    2017-07-07
  • SpringBoot使用前缀树实现敏感词过滤示例

    SpringBoot使用前缀树实现敏感词过滤示例

    最近项目用到了敏感词过滤,本文主要就来介绍一下SpringBoot使用前缀树实现敏感词过滤示例,具有一定的参考价值,感兴趣的可以了解一下
    2023-10-10

最新评论