Java Spring-无法将图像保存到静态文件夹 [英] Java Spring - Can't save image to static folder

查看:37
本文介绍了Java Spring-无法将图像保存到静态文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图像保存到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,以便能够从胸腺叶访问它。

谢谢。

推荐答案

问题是,您可能能够在开发阶段将文件保存在项目目录中,但一旦将项目导出为应用程序包(<[2-3]-应用程序、.war-存档等),就不可能做到这一点,因为在这一点上,以前是文件系统上的实际目录的所有内容现在都是单个文件。

以下是如何通过将图像保存在可配置文件夹中来实现此功能的示例:

我从未用Kotlin编写过一行代码。我希望这个示例能够帮助您,即使它是用Java编写的。

这是一个示例控制器,它接受要在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 == -1) {
            return Optional.empty();
        } else {
            return Optional.of(fileName.substring(indexOfLastDot + 1));
        }
    }
}

假设您上传了文件结尾为.png、id为HelloWorld的am图片,然后可以使用url访问该图片: http://localhost:8080/image/HelloWorld.png

使用此URL,您还可以在任何胸腺叶模板中引用该图像:

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

这篇关于Java Spring-无法将图像保存到静态文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆