設(shè)置Content-Disposition響應(yīng)頭類型
"inline"查看預(yù)覽 ; "attachment"下載;文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-819266.html
inline:表示回復(fù)中的消息體會(huì)以頁(yè)面的一部分或者整個(gè)頁(yè)面的形式展示
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 對(duì)應(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)用或測(cè)試文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-819266.html
/**
* 查詢文件
* @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返回文件時(shí)為圖片或pdf等設(shè)置在線預(yù)覽或下載的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!