Java實現(xiàn)文件圖片的預覽和下載功能
Java實現(xiàn)文件(圖片)的預覽和下載
@ApiOperation("訪問文件") @GetMapping("/download/{name}") public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException { //動態(tài)獲取圖片存放位置 // String path = getUploadPath();//獲取當前系統(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")) { //預覽時不需設置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(); }
注意:踩過的坑,文件名不可以帶*號,帶*會報java.io.FileNotFoundException
通過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(); } // 設置響應頭 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename()); // 返回文件作為響應 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(); } } }
方法補充
方法一:
該代碼段展示了如何在Spring Boot中實現(xiàn)文件的預覽和下載功能。通過HttpServletRequest和HttpServletResponse,根據(jù)請求參數(shù)判斷是預覽還是下載,并設置相應的內容類型和Content-Disposition。文件路徑為固定目錄下,讀取文件內容并寫入響應流。
具體如下
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預覽,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 { //預覽時不需設置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 實現(xiàn)圖片或文件在線預覽及下載
完整代碼
@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(); // 設置response的Header // 解決跨域 response.addHeader("Access-Control-Allow-Origin", "*"); boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType); // 圖片預覽 if (b) { response.setContentType("image/" + fileType); } else if ("pdf".equalsIgnoreCase(fileType)) { // pdf 預覽 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(); } }
到此這篇關于Java實現(xiàn)文件圖片的預覽和下載功能的文章就介紹到這了,更多相關Java圖片預覽和下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java org.springframework.boot 對redis操作方法
在Spring Boot項目中操作Redis,你可以使用Spring Data Redis,Spring Data Redis是Spring提供的一個用于簡化Redis數(shù)據(jù)訪問的模塊,它提供了一個易于使用的編程模型來與Redis交互,本文給大家介紹java org.springframework.boot 對redis操作方法,感興趣的朋友一起看看吧2025-04-04Springboot中的異步任務執(zhí)行及監(jiān)控詳解
這篇文章主要介紹了Springboot中的異步任務執(zhí)行及監(jiān)控詳解,除了自己實現(xiàn)線程外,springboot本身就提供了通過注解的方式,進行異步任務的執(zhí)行,下面主要記錄一下,在Springboot項目中實現(xiàn)異步任務,以及對異步任務進行封裝監(jiān)控,需要的朋友可以參考下2023-10-10在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程
Thymeleaf是一款開源的模板引擎,它允許前端開發(fā)者使用HTML與XML編寫動態(tài)網(wǎng)頁,hymeleaf的主要特點是將表達式語言嵌入到HTML結構中,它支持Spring框架,使得在Spring MVC應用中集成非常方便,本文給大家介紹了在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程2024-09-09