Java Springboot如何基于圖片生成下載鏈接
現(xiàn)有一些圖片在服務(wù)器上的鏈接,在瀏覽器中打開(kāi)這些鏈接是直接顯示在瀏覽器頁(yè)面的形式。
現(xiàn)在需要生成這些圖片的單獨(dú)下載以及打包下載鏈接,即在瀏覽器中打開(kāi)下載鏈接后彈出下載框提示下載。由于前端存在跨域問(wèn)題,所以圖片下載由后臺(tái)接口完成。
首先編寫(xiě)文件下載工具類:
import java.net.URL; import java.net.MalformedURLException; import org.apache.commons.io.FileUtils; public class FileDownloadUtil { /** * 下載文件---返回下載后的文件存儲(chǔ)路徑 * * @param url 文件路徑 * @param dir 目標(biāo)存儲(chǔ)目錄 * @param fileName 存儲(chǔ)文件名 * @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) { // 拼接完整圖片路徑。這里填寫(xiě)圖片鏈接 String urlPath = ""; // 獲取圖片文件后綴名 String postfix = "." + StringUtils.substringAfterLast(url, "."); // 獲取當(dāng)前類的所在項(xiàng)目路徑 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)); } }
因?yàn)槭荊ET請(qǐng)求,所以直接拼接接口路由+參數(shù),用瀏覽器打開(kāi)就能彈出下載。
至此單張圖片下載接口結(jié)束。
多張圖片打包下載
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)); } // 獲取當(dāng)前類的所在項(xiàng)目路徑 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("壓縮完成,耗時(shí):" + (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請(qǐng)求,所以也是拼接接口路由+參數(shù),用瀏覽器打開(kāi)就能彈出下載。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
詳解springboot整合ehcache實(shí)現(xiàn)緩存機(jī)制
這篇文章主要介紹了詳解springboot整合ehcache實(shí)現(xiàn)緩存機(jī)制,ehcache提供了多種緩存策略,主要分為內(nèi)存和磁盤(pán)兩級(jí),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01Spring?Validation實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的示例
Spring?Validation其實(shí)就是對(duì)Hibernate?Validator進(jìn)一步的封裝,方便在Spring中使用,這篇文章主要介紹了Spring?Validation實(shí)現(xiàn)數(shù)據(jù)校驗(yàn)的示例,需要的朋友可以參考下2023-03-03解決SpringMVC 返回Java8 時(shí)間JSON數(shù)據(jù)的格式化問(wèn)題處理
本篇文章主要介紹了解決SpringMVC 返回Java8 時(shí)間JSON數(shù)據(jù)的格式化問(wèn)題處理,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02Java 日期格式加上指定月數(shù)(一個(gè)期限)得到一個(gè)新日期的實(shí)現(xiàn)代碼
這篇文章主要介紹了Java 日期格式加上指定月數(shù)(一個(gè)期限)得到一個(gè)新日期的實(shí)現(xiàn)代碼,需要的朋友可以參考下2018-05-05