我是 SpringBoot Web 開發人員的新手。我需要將影像保存到當前專案中的目錄中。我已將路徑指定為“String uploaddir = "./src/main/imageuploads/" savedadvert.getId();” 但是影像沒有保存到eclipse專案中的“./src/main/imageuploads/”目錄。
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(@RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "./src/main/imageuploads/" savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
這是 ref 的 saveFile 方法。
public static void saveFile(MultipartFile multipartFile, String fileName, String uploadDir) throws IOException {
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = multipartFile.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
System.out.println(filePath.toFile().getAbsolutePath());
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ioe) {
throw new IOException("Could not save image file: " fileName, ioe);
}
}
我需要把圖片上傳到這個目錄,

當我獲得絕對路徑時,它顯示為“/Users/chathura/eclipse/jee-2021-03/Eclipse.app/Contents/MacOS/./src/main/imageuploads/24/new file.jpg”。無法進入該目錄,但我可以使用終端訪問該目錄。

請告訴我這里的錯誤是什么?
注意:我正在使用 macos
提前致謝
uj5u.com熱心網友回復:
- 你能試試 'src/main/resources/imagesuploads'(沒有 .)
- 提醒一下:當您打包應用程式(生產模式)時,此目錄將消失
- 此目錄應該可以從外部檔案(例如 application.properties)配置
uj5u.com熱心網友回復:
謝謝阿里,您的回復為解決方案提供了線索。因此,我的專案位于 MacOS 磁區上,未經許可我無法寫入檔案。我只是將位置更改為另一個磁區并且它起作用了。
@RequestMapping(value="/upload", method = RequestMethod.POST)
public String FileUpload(@RequestParam("file1Url") MultipartFile multipartfile, Model model) throws IOException {
model.addAttribute("advertsim",new advertsummary());
advertsummary advert = new advertsummary();
String file1Urlname= StringUtils.cleanPath(multipartfile.getOriginalFilename());
advert.setFile1Url(file1Urlname);
advertsummary savedadvert = AdvertService.addadvert(advert);
String uploaddir = "/Volumes/My Data/Fileupload" savedadvert.getId();
FileUploadUtil.saveFile(multipartfile, file1Urlname, uploaddir);
return "uploadview";
}
謝謝
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335014.html
標籤:爪哇 弹簧靴 行家 java.nio.file
上一篇:生產者模板。駱駝。如何添加附件
