图像在重新启动应用程序之前不会加载。

huangapple go评论68阅读模式
英文:

Image is not loading until restart application

问题

在将图像上传至 dataBaseTest\src\main\resources\static\uploads\ 位置之后,我无法在网页上显示它,直到应用程序重新启动。我知道这是因为static文件夹只有在服务器启动时才会加载,但该问题如何解决呢?我尝试直接将图像上传到\dataBaseTest\target\classes\static\uploads\,这样可以正常工作(上传后立即加载),但这似乎不太正确。我还尝试过在 "pom.xml" 中添加以下配置:

<configuration>
    <addResources>true</addResources>
</configuration>

但是什么也没改变。

我也尝试过使用 addResourceHandlers,但整个 static 文件夹似乎停止工作了。

我正在使用 Spring Boot Dev Tools,所以应用程序会自动重新启动,但我想解决这个问题而无需重新启动。

~ 编辑

错误代码

~ 编辑 2

我在 IntelliJ Tomcat 中运行此应用程序。

这是我的 FileUploadService

public String uploadImage(MultipartFile multipartFile) throws IOException {
    String fileName = multipartFile.getOriginalFilename();
    Path uploadDirectory = Paths.get("src/main/resources/static/uploads/");
    //Path uploadDirectory = Paths.get("target\\classes\\static\\uploads\\");

    try (InputStream inputStream = multipartFile.getInputStream()) {
        String path = UUID.randomUUID() + "-" + fileName;
        Path filePath = uploadDirectory.resolve(path);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        return path;
    } catch (IOException ioException){
        throw new IOException("Error saving uploaded file: " + fileName, ioException);
    }
}

这是控制器

public String displayArticles(Model model){
    final String currentName = SecurityContextHolder.getContext().getAuthentication().getName();
    System.out.println(currentName);
    model.addAttribute("currentUser", currentName);
    model.addAttribute("articles", repoArticle.findAll());
    model.addAttribute("comments", commentService.findAll());
    model.addAttribute("likes", repoLikes.findByUsername(currentName));
    return "display_articles";
}

这是 HTML

<div class="image">
    <img th:src="'../uploads/' + ${article.path}" alt="">
</div>

文件夹结构

英文:

After upload an image to location dataBaseTest\src\main\resources\static\uploads\ I can't display it on webpage, until application is restarted. I know it's because folder static is loaded only when server is starting, but how can it be solved? I've tried to upload image directly to \dataBaseTest\target\classes\static\uploads\ and it is working fine (loading immedietaly after upload), but it's just not seems to be correct. Also I tried to add

&lt;configuration&gt;
	&lt;addResources&gt;true&lt;/addResources&gt;
&lt;/configuration&gt;

to "pom.xml" but nothing has changed.

I've also tried to use addResourceHandlers but whole folder static seems to stop working.

I'm using Spring boot dev Tools, so the app is restarting automatically, but I'm trying to solve it without any restart.

~ edit

error code

~ edit 2

I'm running this app in intellij Tomcat.

this is my FileUploadService

public String uploadImage(MultipartFile multipartFile) throws IOException {


    String fileName = multipartFile.getOriginalFilename();
    Path uploadDirectory = Paths.get(&quot;src/main/resources/static/uploads/&quot;);
    //Path uploadDirectory = Paths.get(&quot;target\\classes\\static\\uploads\\&quot;);


    try (InputStream inputStream = multipartFile.getInputStream()) {
        String path = UUID.randomUUID()+ &quot;-&quot; + fileName;
        Path filePath = uploadDirectory.resolve(path);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
        return path;
    } catch (IOException ioException){
        throw new IOException(&quot;Error saving uploaded file: &quot; + fileName, ioException);
    }
}

this is controller

public String displayArticles(Model model){
    final String currentName = SecurityContextHolder.getContext().getAuthentication().getName();
    System.out.println(currentName);
    model.addAttribute(&quot;currentUser&quot;, currentName);
    model.addAttribute(&quot;articles&quot;, repoArticle.findAll());
    model.addAttribute(&quot;comments&quot;, commentService.findAll());
    model.addAttribute(&quot;likes&quot;, repoLikes.findByUsername(currentName));
    return &quot;display_articles&quot;;
}

this is html

            &lt;div class=&quot;image&quot;&gt;
                &lt;img th:src=&quot;&#39;../uploads/&#39; + ${article.path}&quot; alt=&quot;&quot;&gt;
            &lt;/div&gt;

folder tree

答案1

得分: 0

这应该会将您的图像直接保存到/target文件夹,因此立即可用(请注意,应用程序资源和代码在应用程序运行时存储在/target中)。

//使用类加载器来获取资源路径,而不是硬编码它
final String uploadLocation = getClass().getClassLoader().getResource("static/uploads").toString();
//我们应该去掉file:/,因此截取字符串
final Path uploadDirectory = Paths.get(uploadLocation.substring(6, uploadLocation.length()));

其余的代码可以保持不变。

或者,您可以指定自己的上传文件夹。例如,

application.properties

#用户主目录应该在任何计算机上都存在
files.upload.location=${user.home}/myApp/fileUpload

然后,您可以在您的控制器中简单地检索它,

@Autowired
private Environment environment;
...

final String uploadLocation = environment.getProperty("files.upload.location");

希望这有所帮助。

英文:

This should save your image directly to /target folder and thus make it immediately available (note that both the application resources and code are stored in /target when the app is running)

    //use the class loader to get the resource path, rather than hardcoding it
	final String uploadLocation = getClass().getClassLoader().getResource(&quot;static/uploads&quot;).toString();
	//we should get rid of file:/, hence the substring
	final Path uploadDirectory = Paths.get(uploadLocation.substring(6, uploadLocation.length()) );

The rest of the code can remain the same.

Alternatively, you can specify your own upload folder. For instance,

application.properties

 #user home should be present on any computer
 files.upload.location=${user.home}/myApp/fileUpload

You would then simply retrive it in your controller,

 @Autowired 
 private Environment environment;
...

final String uploadLocation =    environment.getProperty(&quot;files.upload.location&quot;);

Hope this helps.

huangapple
  • 本文由 发表于 2023年2月9日 03:01:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75390537.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定