JavaでPDFファイルをブラウザに表示にするには、以下のURLが参考になると思います。
拡張子がPDFを保存できるフォルダを作り、
書類をアップロード。保存されていればリンクを押したら表示できる機能を作っています。
現在、フォルダを作成し、書類をアップロードするところまではできたのですが、表示の仕方がわかりません。
例)
examlie.pdf
または、問題・エラーが起きている画像をここにドラッグアンドドロップ
【pdf.html】
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>top page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>ファイルアップロード</h2>
<form method="post" enctype="multipart/form-data" th:action="@{/upload}" th:object="${form}" >
<input th:field="*{file}" type="file" multiple/>
<input type="submit" value="アップロード"/>
</form>
<ul>
<li>
<a href="C:/Users/Education//Desktop/save/examlie.pdf">examlie.pdf</a>
</li>
</ul>
</body>
</html>
例)
@Controller
public class FileUploadController {
private String getExtension(String filename) {
int dot = filename.lastIndexOf(".");
if (dot > 0) {
return filename.substring(dot).toLowerCase();
}
return "";
}
private String getUploadFileName(String fileName) {
return fileName + "_" +
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
.format(LocalDateTime.now())
+ getExtension(fileName);
}
private void createDirectory() {
Path path = Paths.get("C:/Users/Education/Desktop/save");
if (!Files.exists(path)) {
try {
Files.createDirectory(path);
} catch (Exception e) {
}
}
}
private void savefile(MultipartFile file) {
String filename = getUploadFileName(file.getOriginalFilename());
Path uploadfile = Paths.get("C:/Users/Education//Desktop/save/" + filename);
try (OutputStream os = Files.newOutputStream(uploadfile, StandardOpenOption.CREATE)) {
byte[] bytes = file.getBytes();
os.write(bytes);
} catch (IOException e) {
}
}
private void savefiles(List<MultipartFile> multipartFiles) {
createDirectory();
for (MultipartFile file : multipartFiles) {
savefile(file);
}
}
@RequestMapping(path = "/", method = RequestMethod.GET)
String uploadview(Model model) {
model.addAttribute("form", new UploadForm());
return "index";
}
@RequestMapping(path = "/upload", method = RequestMethod.POST)
String upload(Model model, UploadForm form) {
if (form.getFile()==null || form.getFile().isEmpty()) {
return "index";
}
savefiles(form.getFile());
return "redirect:/";
}
}
html側でリスト形式にし、aタグを使えばでるのかなと思ったのですがそんな簡単なことではなかったです。
JavaでPDFファイルをブラウザに表示にするには、以下のURLが参考になると思います。
Web サーバー (開発用で可) を使いましょう。
aタグを使えばでるのかなと思ったのですがそんな簡単なことではなかったです。
そのとおりの簡単なことなのですが、pdf ファイルのアップロード先のフォルダを、ブラウザからアクセスできる Web サーバーのフォルダにしてください。
<a href="C:/Users/Education//Desktop/save/examlie.pdf">examlie.pdf</a>
ではダメだと思います。C:/Users/Education/Desktop/save というフォルダに pdf ファイルを保存するのであれば、そのフォルダを Web サーバーの仮想ディレクトリに設定してください。
try this.
href: http://ip:port/pdf/download/「PdfFileName」
@GetMapping("/pdf/download/{fileName}")
public void download(@PathVariable String fileName,
HttpServletResponse response) throws IOException {
response.setHeader("Content-Type", "application/pdf");
FileInputStream in = new FileInputStream(
"C:/Users/Education//Desktop/save/" + fileName + ".pdf");
ServletOutputStream outputStream = response.getOutputStream();
byte[] data = new byte[1024];
while(in.read(data, 0, 1024) != -1) {
outputStream.write(data);
}
outputStream.flush();
in.close();
}
@quint555
Questionerいただいたものを元に実行してみたのですがうまくいきません。
ダウンロードするという手順を組み込んでいないからでしょうか。
それと下記はHTMLのaタグ内に記載するものでしょうか。
href: http://ip:port/pdf/download/「PdfFileName」
バックエンドからファイルのリストを読み込み、それらを繰り返し、ページに表示する。完全なコードは以下の通り。
<!DOCTYPE HTML>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/upload" >
<input type="file" name="file"/>
<input type="submit"/>
</form>
<ul>
<!-- リンクを作成 -->
<th:block th:each="file:${files}">
<li><a target="_blank" th:href="'/download/' + ${file}" th:text="${file}"/></li>
</th:block>
</ul>
</body>
</html>
package com.example.demo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
@Controller
public class FileController {
private String path = "C:/Users/Education/Desktop/save";
@GetMapping("/index")
public String index(Model model) {
List<String> files = Arrays.stream(
new File(path).listFiles()).map(o -> o.getName()).collect(Collectors.toList());
// ファイル名表示用
model.addAttribute("files", files);
return "index";
}
@PostMapping("/upload")
public String upload(@RequestParam("file")MultipartFile file) throws IOException {
String name = file.getOriginalFilename();
InputStream in = file.getInputStream();
OutputStream outputStream = new FileOutputStream(path + "/" + name);
byte[] data = new byte[1024];
int len;
while((len=in.read(data, 0, 1024))!= -1) {
outputStream.write(data, 0, len);
}
outputStream.flush();
outputStream.close();
in.close();
return "redirect:index";
}
// ファイルをダウンロードする
@GetMapping("/download/{fileName}")
public void download(@PathVariable String fileName,
HttpServletResponse response) throws IOException {
response.setHeader("Content-Type", "application/pdf");
FileInputStream in = new FileInputStream(
path + "/" + fileName );
ServletOutputStream outputStream = response.getOutputStream();
byte[] data = new byte[1024];
int len;
while((len=in.read(data, 0, 1024))!= -1) {
outputStream.write(data, 0, len);
}
outputStream.flush();
outputStream.close();
in.close();
}
}
@quint555
Questionerありがとうございました。理解することができました!
ブラウザ依存でよければ
<iframe src="webサーバのパス/examlie.pdf" width="100%" height="600"></iframe>
@quint555
Questionerすごいです。
とても勉強になりました、ありがとうございます。
横レス失礼します。
<iframe src="webサーバのパス/examlie.pdf" width="100%" height="600"></iframe>
でよければ、最初の質問に書いてあった、
<a href="C:/Users/Education//Desktop/save/examlie.pdf">examlie.pdf</a>
を
<a href="webサーバのパス/examlie.pdf">examlie.pdf</a>
にすれば済むはずです。