Java返回文件時為圖片或pdf等設(shè)置在線預(yù)覽或下載功能
更新時間:2024年01月16日 09:38:20 作者:菜鳥程序猿、
這篇文章主要介紹了Java返回文件時為圖片或pdf等設(shè)置在線預(yù)覽或下載功能,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
設(shè)置Content-Disposition響應(yīng)頭類型
"inline"查看預(yù)覽 ; "attachment"下載;
inline:表示回復(fù)中的消息體會以頁面的一部分或者整個頁面的形式展示
attchment:以附件形式被下載到本地;
/**
* 文件或圖片預(yù)覽/下載工具類
* @author zh、
* @data 2024/1/11 18:35
*/
@Component
@Slf4j
public class FileHttpUtil {
/**
* 根據(jù)物理路徑文件 獲取 下載/預(yù)覽 文件
* @param file 文件
* @param type 設(shè)置響應(yīng)頭類型 "inline"查看 "attachment"下載
* @param fileName 文件名
* @return 對應(yīng)類型響應(yīng)文件
*/
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>接口調(diào)用或測試
/**
* 查詢文件
* @param filePath文件地址 物理路徑
* @param type 設(shè)置響應(yīng)頭類型 "inline"查看 "attachment"下載
* @return 響應(yīng)文件
* @throws IOException
*/
@GetMapping(value = "/file")
public ResponseEntity<?> file(String filePath,String type){
//根據(jù)文件路徑去文件服務(wù)獲取文件
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();
}
}到此這篇關(guān)于Java返回文件時為圖片或pdf等設(shè)置在線預(yù)覽或下載的文章就介紹到這了,更多相關(guān)java pdf在線預(yù)覽或下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringMVC通過Ajax處理Json數(shù)據(jù)的步驟詳解
這篇文章主要介紹了SpringMVC通過Ajax處理Json數(shù)據(jù)的步驟詳解,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04

