依賴方面 創(chuàng)建的是 接口web項(xiàng)目就好了
然后包管理工具打開(kāi)需要這些
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
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.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
然后 例如這里我要預(yù)覽 本地 E盤下的 ydzxmgf下的git分支管理規(guī)范.pdf文件 就可以這樣寫文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-719812.html
@GetMapping("/pdf")
public ResponseEntity<Resource> previewPdfFile() throws IOException {
// 指定文件路徑
String filePath = "E:/ydzxmgf/git分支管理規(guī)范.pdf";
// 創(chuàng)建文件資源
File file = new File(filePath);
Path path = Paths.get(file.getAbsolutePath());
Resource resource = new FileSystemResource(file);
// 設(shè)置響應(yīng)頭
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + file.getName());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
// 返回響應(yīng)實(shí)體
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.APPLICATION_PDF)
.body(resource);
}
然后在瀏覽器上訪問(wèn)接口
就達(dá)到這個(gè)預(yù)覽的效果了文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-719812.html
到了這里,關(guān)于java springboot2.7 寫一個(gè)本地 pdf 預(yù)覽的接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!