1 问题描述
服务执行时,读取 jar 所在目录的外部文件
2 解决方案
通过 ApplicationHome 获取 jar 所在目录路径
1 2
| ApplicationHome home = new ApplicationHome(TestSpringBootApplication.class); String jarPath = home.getDir().toString();
|
3 案例
1)建立一个 Controller,响应更新所在目录路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| @RestController public class ActionController { @RequestMapping("/dir") public String updateDirMsg() { ApplicationHome home = new ApplicationHome(TestSpringBootApplication.class); String jarPath = home.getDir().toString();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(jarPath + "/path.txt", true))) { writer.write(LocalDateTime.now() + " :" + jarPath); writer.newLine(); writer.flush(); } catch (IOException e) { System.err.println("写入文件时发生错误: " + e.getMessage()); } return jarPath; } }
|
2)更进一步,利用路径保存上传的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| @Controller public class FileUploadController {
private static final String UPLOAD_ROOT_DIR = new ApplicationHome(TestSpringBootApplication.class).getDir().toString();
@PostMapping("/upload") public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("上传的压缩包不能为空"); }
try { Path targetPath = Paths.get(UPLOAD_ROOT_DIR, file.getOriginalFilename()); Files.createDirectories(targetPath.getParent()); file.transferTo(targetPath.toFile());
unzipFile(targetPath.toString(), UPLOAD_ROOT_DIR);
FileSystemResource fileSystemResource = new FileSystemResource(targetPath.toFile()); return ResponseEntity.ok().body(String.valueOf(fileSystemResource));
} catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(500).body("上传过程中发生错误:" + e.getMessage()); } }
private void unzipFile(String zipFilePath, String destDir) throws IOException { try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFilePath))) { ZipEntry entry = zis.getNextEntry(); while (entry != null) { Path filePath = Paths.get(destDir, entry.getName()); if (!entry.isDirectory()) { Files.createDirectories(filePath.getParent()); Files.copy(zis, filePath); } else { Files.createDirectories(filePath); } zis.closeEntry(); entry = zis.getNextEntry(); } } }
|
相应的前端案例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Upload Zip File</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body>
<div class="container mt-4"> <h2>Upload and Extract ZIP File</h2> <form id="uploadForm" enctype="multipart/form-data"> <div class="mb-3"> <label for="zipFile" class="form-label">Select a ZIP file to upload:</label> <input type="file" class="form-control" id="zipFile" name="file" accept=".zip"> </div> <button type="submit" class="btn btn-primary" id="uploadButton">Upload & Extract</button> </form> <div id="responseMessage"></div> </div>
<script> document.addEventListener('DOMContentLoaded', function() { const uploadForm = document.getElementById('uploadForm'); const zipFileInput = document.getElementById('zipFile'); const responseMessage = document.getElementById('responseMessage'); const uploadButton = document.getElementById('uploadButton');
uploadButton.addEventListener('click', function(event) { event.preventDefault(); // 阻止表单默认提交行为
if (!zipFileInput.files.length) { responseMessage.textContent = "Please select a ZIP file."; return; }
const formData = new FormData(uploadForm);
fetch('/upload', { method: 'POST', body: formData, }) .then(response => response.text()) .then(data => { responseMessage.textContent = data; // 在这里可以添加跳转到查看解压后文件列表的逻辑 }) .catch(error => { responseMessage.textContent = "An error occurred while uploading the file: " + error; });
// 清空已选择的文件 zipFileInput.value = ''; }); }); </script>
</body> </html>
|