Java實(shí)現(xiàn)文件圖片的預(yù)覽和下載功能
Java實(shí)現(xiàn)文件(圖片)的預(yù)覽和下載
@ApiOperation("訪問(wèn)文件") @GetMapping("/download/{name}") public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException { //動(dòng)態(tài)獲取圖片存放位置 // String path = getUploadPath();//獲取當(dāng)前系統(tǒng)路徑 String path = upload; String imagePath = path + File.separator + name; if (!new File(imagePath).exists()) { return; } if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("gif") || name.endsWith("jpeg")) { //預(yù)覽時(shí)不需設(shè)置Content-Disposition response.setContentType("image/jpeg;charset=utf-8");//圖片 }else { //下載 response.setContentType("application/octet-stream");//文件 response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(name, "UTF-8")); } ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(Files.readAllBytes(Paths.get(path).resolve(name))); outputStream.flush(); outputStream.close(); }
注意:踩過(guò)的坑,文件名不可以帶*號(hào),帶*會(huì)報(bào)java.io.FileNotFoundException
通過(guò)mvc與hutool工具集下載在resources目錄下的文件,注意引入的包
package com.example.controller; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.nio.file.Files; @RestController @RequestMapping("/api/files") public class FileDownloadController { @GetMapping("/download") public ResponseEntity<Resource> downloadFile() { String fileName = "example.txt"; // 要下載的文件名 try { // 從 resources 目錄加載文件 ClassPathResource resource = new ClassPathResource(fileName); if (!resource.exists()) { return ResponseEntity.notFound().build(); } // 設(shè)置響應(yīng)頭 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()); // 返回文件作為響應(yīng) return ResponseEntity.ok() .headers(headers) .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM) .body(resource); } catch (IOException e) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
方法補(bǔ)充
方法一:
該代碼段展示了如何在Spring Boot中實(shí)現(xiàn)文件的預(yù)覽和下載功能。通過(guò)HttpServletRequest和HttpServletResponse,根據(jù)請(qǐng)求參數(shù)判斷是預(yù)覽還是下載,并設(shè)置相應(yīng)的內(nèi)容類型和Content-Disposition。文件路徑為固定目錄下,讀取文件內(nèi)容并寫入響應(yīng)流。
具體如下
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; /** * @author long * @version 1.0.0 * @ClassName FileController * @Description TODO * @createTime 2022.03.18 18:47 */ @RestController @RequestMapping("/demo") public class FileController { @GetMapping("/file") public void filePreviewOrDownload(HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("fileName"); //type. p預(yù)覽,d下載 String type = request.getParameter("type"); response.reset(); response.setCharacterEncoding("UTF-8"); File file = new File("C:\\Users\\long\\Desktop\\" + fileName); FileInputStream fis = new FileInputStream(file); if ("d".equalsIgnoreCase(type)) { //下載 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))); } else { //預(yù)覽時(shí)不需設(shè)置Content-Disposition // response.setContentType("application/octet-stream"); // response.setContentType("text/html;charset=UTF-8"); // response.setHeader("Content-Disposition","inline;filename=" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."))); } OutputStream os = response.getOutputStream(); byte[] bytes = new byte[1024]; int length = 0; while ((length = fis.read(bytes)) != -1) { os.write(bytes, 0, length); } os.close(); fis.close(); } }
方法二:
Java 實(shí)現(xiàn)圖片或文件在線預(yù)覽及下載
完整代碼
@GetMapping("/downFile") public void downFile(HttpServletResponse response, HttpServletRequest request) { try { // File file = new File("C:\\Users\\hnsh\\Pictures\\鐵山靠.png"); File file = new File("F:\\BaiduNetdiskDownload\\activiti教程 (1).pdf"); String filename = file.getName(); String fileType = filename.substring(filename.indexOf(".") + 1); // 以流的形式下載文件。 FileInputStream fileInputStream = new FileInputStream(file); InputStream fis = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[1024]; int len = 0; // 清空response response.reset(); // 設(shè)置response的Header // 解決跨域 response.addHeader("Access-Control-Allow-Origin", "*"); boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType); // 圖片預(yù)覽 if (b) { response.setContentType("image/" + fileType); } else if ("pdf".equalsIgnoreCase(fileType)) { // pdf 預(yù)覽 response.setContentType("application/pdf"); } else { // 直接下載 response.setContentType("application/text;chartset=utf-8"); response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8")); response.addHeader("Content-Length", "" + file.length()); } OutputStream toClient = new BufferedOutputStream(response.getOutputStream()); int a = 0; while ((len = fis.read(buffer)) != -1) { a = len + a; toClient.write(buffer, 0, len); } toClient.flush(); toClient.close(); } catch (IOException ex) { ex.printStackTrace(); } }
到此這篇關(guān)于Java實(shí)現(xiàn)文件圖片的預(yù)覽和下載功能的文章就介紹到這了,更多相關(guān)Java圖片預(yù)覽和下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java org.springframework.boot 對(duì)redis操作方法
在Spring Boot項(xiàng)目中操作Redis,你可以使用Spring Data Redis,Spring Data Redis是Spring提供的一個(gè)用于簡(jiǎn)化Redis數(shù)據(jù)訪問(wèn)的模塊,它提供了一個(gè)易于使用的編程模型來(lái)與Redis交互,本文給大家介紹java org.springframework.boot 對(duì)redis操作方法,感興趣的朋友一起看看吧2025-04-04Java為什么使用補(bǔ)碼進(jìn)行計(jì)算的原因分析
這篇文章主要介紹了Java為什么使用補(bǔ)碼進(jìn)行計(jì)算的原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08Java中Excel高效解析工具EasyExcel的實(shí)踐
EasyExcel是阿里巴巴開源的一個(gè)excel處理框架,已使用簡(jiǎn)單,節(jié)省內(nèi)存著稱,下面這篇文章主要給大家介紹了關(guān)于Java中Excel高效解析工具EasyExcel實(shí)踐的相關(guān)資料,需要的朋友可以參考下2022-04-04Java判斷2個(gè)List集合是否相等(不考慮元素的順序)
今天小編就為大家分享一篇關(guān)于Java判斷2個(gè)List集合是否相等(不考慮元素的順序)的文章,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10Springboot中的異步任務(wù)執(zhí)行及監(jiān)控詳解
這篇文章主要介紹了Springboot中的異步任務(wù)執(zhí)行及監(jiān)控詳解,除了自己實(shí)現(xiàn)線程外,springboot本身就提供了通過(guò)注解的方式,進(jìn)行異步任務(wù)的執(zhí)行,下面主要記錄一下,在Springboot項(xiàng)目中實(shí)現(xiàn)異步任務(wù),以及對(duì)異步任務(wù)進(jìn)行封裝監(jiān)控,需要的朋友可以參考下2023-10-10在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程
Thymeleaf是一款開源的模板引擎,它允許前端開發(fā)者使用HTML與XML編寫動(dòng)態(tài)網(wǎng)頁(yè),hymeleaf的主要特點(diǎn)是將表達(dá)式語(yǔ)言嵌入到HTML結(jié)構(gòu)中,它支持Spring框架,使得在Spring MVC應(yīng)用中集成非常方便,本文給大家介紹了在SpringBoot當(dāng)中使用Thymeleaf視圖解析器的詳細(xì)教程2024-09-09