Java返回文件時為圖片或pdf等設置在線預覽或下載功能
更新時間:2024年01月16日 09:38:20 作者:菜鳥程序猿、
這篇文章主要介紹了Java返回文件時為圖片或pdf等設置在線預覽或下載功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
設置Content-Disposition響應頭類型
"inline"查看預覽 ; "attachment"下載;
inline:表示回復中的消息體會以頁面的一部分或者整個頁面的形式展示
attchment:以附件形式被下載到本地;
/** * 文件或圖片預覽/下載工具類 * @author zh、 * @data 2024/1/11 18:35 */ @Component @Slf4j public class FileHttpUtil { /** * 根據物理路徑文件 獲取 下載/預覽 文件 * @param file 文件 * @param type 設置響應頭類型 "inline"查看 "attachment"下載 * @param fileName 文件名 * @return 對應類型響應文件 */ public static ResponseEntity<?> getResponseEntity(byte[] file , String type , String fileName ){ ResponseEntity.BodyBuilder responseEntity = ResponseEntity.ok(); HttpHeaders httpHeaders = new HttpHeaders(); Tika tika = new Tika(); String mediaType = tika.detect(file); httpHeaders.setContentType(MediaType.parseMediaType(mediaType)); httpHeaders.setContentDisposition(ContentDisposition.builder(type) .filename(URLEncoder.encode(fileName )).build()); httpHeaders.setCacheControl(CacheControl.noCache()); //httpHeaders.setCacheControl(CacheControl.maxAge(10, TimeUnit.MINUTES)); return responseEntity.headers(httpHeaders).body(file ); } 需要的pom依賴文件 <dependency> <groupId>org.apache.tika</groupId> <artifactId>tika-core</artifactId> <version>1.28.4</version> </dependency>
接口調用或測試
/** * 查詢文件 * @param filePath文件地址 物理路徑 * @param type 設置響應頭類型 "inline"查看 "attachment"下載 * @return 響應文件 * @throws IOException */ @GetMapping(value = "/file") public ResponseEntity<?> file(String filePath,String type){ //根據文件路徑去文件服務獲取文件 File file = new File(filePath); try (FileInputStream fileInputStream = new FileInputStream(file)) { byte[] buf = new byte[fileInputStream.available()]; fileInputStream.read(buf); return FileHttpUtil.getResponseEntity(buf, type,file .getName()); } catch (IOException e) { e.printStackTrace(); } }
到此這篇關于Java返回文件時為圖片或pdf等設置在線預覽或下載的文章就介紹到這了,更多相關java pdf在線預覽或下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringMVC通過Ajax處理Json數(shù)據的步驟詳解
這篇文章主要介紹了SpringMVC通過Ajax處理Json數(shù)據的步驟詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04