Java Spring-无法将图像保存到静态文件夹

原学程将引见Java Spring-没法将图象保留到动态文件夹的处置办法,这篇学程是从其余处所瞅到的,而后减了1些海外法式员的疑问与解问,愿望能对于您有所赞助,佳了,上面开端进修吧。

Java Spring-无法将图像保存到静态文件夹 教程 第1张

成绩描写

我想将图象保留到resources/static/photos文件,但是Java/Kotlin找没有到它。但是它发明project/photos很佳。

这是用科特林编辑的代码,但是我以为这可有可无

 override fun saveImage(imageFile: MultipartFile, id: String) {
  val bytes = imageFile.bytes

  val path = Paths.get(
"$imagesFolderPath$id.${imageFile.originalFilename.substringAfter('.')}")
  Files.write(path, bytes)
 }

我须要将此文件保留到resources/static/photos,以就可以或许从胸腺叶拜访它。

感谢。

推举谜底

成绩是,您能够可以或许在开辟阶段将文件保留在项目目次中,但是1旦将项目导出为运用法式包(<[2-3]-应用程序、.war-存档等),便弗成能做到这1面,由于在这1面上,之前是文件体系上的现实目次的一切实质如今皆是单个文件。

以下是怎样经由过程将图象保留在可设置装备摆设文件夹中去完成此功效的示例:

我从未用Kotlin编辑过1言代码。我愿望这个示例可以或许赞助您,即便它是用Java编辑的。

这是1个示例掌握器,它接收要在POST终结面上载并在GET终结面下载的图象:

package example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.PathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Optional;

@RestController
public class MyController {

 private final Path imageStorageDir;

 /*
 The target path can be configured in the application.properties / application.yml or using the parameter -Dimage-storage.dir=/some/path/
  */
 @Autowired
 public MyController(@Value("${image-storage-dir}") Path imageStorageDir) {
  this.imageStorageDir = imageStorageDir;
 }

 @PostConstruct
 public void ensureDirectoryExists() throws IOException {
  if (!Files.exists(this.imageStorageDir)) {
Files.createDirectories(this.imageStorageDir);
  }
 }

 /*
 This enables you to perform POST requests against the "/image/YourID" path
 It returns the name this image can be referenced on later
  */
 @PostMapping(value = "/image/{id}", produces = MediaType.TEXT_PLAIN_VALUE)
 public String uploadImage(@RequestBody MultipartFile imageFile, @PathVariable("id") String id) throws IOException {
  final String fileExtension = Optional.ofNullable(imageFile.getOriginalFilename())
 .flatMap(MyController::getFileExtension)
 .orElse("");

  final String targetFileName = id + "." + fileExtension;
  final Path targetPath = this.imageStorageDir.resolve(targetFileName);

  try (InputStream in = imageFile.getInputStream()) {
try (OutputStream out = Files.newOutputStream(targetPath, StandardOpenOption.CREATE)) {
 in.transferTo(out);
}
  }

  return targetFileName;
 }

 /*
 This enables you to download previously uploaded images
  */
 @GetMapping("/image/{fileName}")
 public ResponseEntity<Resource> downloadImage(@PathVariable("fileName") String fileName) {
  final Path targetPath = this.imageStorageDir.resolve(fileName);
  if (!Files.exists(targetPath)) {
return ResponseEntity.notFound().build();
  }

  return ResponseEntity.ok(new PathResource(targetPath));
 }

 private static Optional<String> getFileExtension(String fileName) {
  final int indexOfLastDot = fileName.lastIndexOf('.');

  if (indexOfLastDot == ⑴) {
return Optional.empty();
  } else {
return Optional.of(fileName.substring(indexOfLastDot + 一));
  }
 }
}

假定您上传了文件开头为.png、id为HelloWorld的am图片,而后不妨应用url拜访该图片:
http://localhost:8080/image/HelloWorld.png

应用此URL,您借不妨在所有胸腺叶模板中援用该图象:

<img th:src="@{/image/HelloWorld.png}"></img>

佳了闭于Java Spring-没法将图象保留到动态文件夹的学程便到这里便停止了,愿望趣模板源码网找到的这篇技巧文章能赞助到年夜野,更多技巧学程不妨在站内搜刮。