静态文件不存在错误。Spring Boot

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

Static file doesn't exist error . Springboot

问题

I am trying to create a folder named img under static folder of spring boot. Wanting it in a dynamic manner / in a way that it works on other people's computers, hence not preferring hardcoding. I am new to spring boot.

The location of the static folder is src/main/resources/static.

The output for the below statement is: C:\Users\Pradeep\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\EventHub\target\classes (providing this thinking this might help)

System.out.println(new ClassPathResource("").getFile().getAbsolutePath());

package com.eventhub.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.eventhub.service.FileService;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String uploadFile(MultipartFile file) throws IOException {
        // getting file name
        String fileName = file.getOriginalFilename();

        // Create a random name for our file to be stored in the db
        String randomId = UUID.randomUUID().toString();

        // adding the extension of our uploaded file
        String fileNameDb = randomId.concat(fileName.substring(fileName.lastIndexOf(".")));

        // full storage path
        // String fileStoragePath = path + File.separator + fileNameDb;

        // creating the storage folder if it doesn't exist (for now img )
        // File f = new File(path);
        // File saveFile = new ClassPathResource("static/img").getFile();
        
        Resource resource = new ClassPathResource("static");
        File staticDir = resource.getFile();
        System.out.println(staticDir);
        File saveFile = new File(staticDir, "img");

        if (!saveFile.exists()) {
            saveFile.mkdirs();
        }

        // copying the file in our folder / directory
        try {
            // Path path1 = Paths.get(saveFile.getAbsolutePath() + File.separator + fileNameDb);
            // Files.copy(file.getInputStream(), path1);

            File targetFile = new File(saveFile, fileNameDb);
            Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            // Files.copy(file.getInputStream(),Paths.get(fileStoragePath));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return fileNameDb;
    }
}

Error when the method is called is:

java.io.FileNotFoundException: class path resource [static] cannot be resolved to URL because it does not exist

When I tried Resource resource = new ClassPathResource("");, the image gets uploaded under the img folder which is created under the target folder.

Resource resource = new ClassPathResource("static/"); and Resource resource = new ClassPathResource("/static"); didn't work.

英文:

I am trying to create a folder named img under static folder of springboot .Wanting it in a dynamic manner / in a way that it works on other peoples computer hence not preferring hardcoding. I am new to springboot

the location of the static folder is src/main/resources/static .

The output for the below statement is :- C:\Users\Pradeep\Documents\workspace-spring-tool-suite-4-4.17.2.RELEASE\EventHub\target\classes ( providing this thinking this might help)

System.out.println(new ClassPathResource("").getFile().getAbsolutePath());

package com.eventhub.service.impl;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.eventhub.service.FileService;
@Service
public class FileServiceImpl implements FileService{
@Override
public String uploadFile(MultipartFile file) throws IOException {
// getting file name
String fileName = file.getOriginalFilename();
// Create a random name for our file to be stored in the db
String randomId = UUID.randomUUID().toString();
// adding the extension of our uploaded file
String fileNameDb = randomId.concat(fileName.substring(fileName.lastIndexOf(".")));
// full storage path
//String fileStoragePath = path + File.separator + fileNameDb;
//creating the storage folder if it doesn't exists (for now img )
//	File f = new File(path);
//	File saveFile = new ClassPathResource("static/img").getFile();
Resource resource = new ClassPathResource("static");
File staticDir = resource.getFile();
System.out.println(staticDir);
File saveFile = new File(staticDir, "img");
if(!saveFile.exists()) {
saveFile.mkdirs();
}
// coping the file in our folder / directory
try {
//			Path path1 =   Paths.get(saveFile.getAbsolutePath() + File.separator + fileNameDb);
//
//			Files.copy(file.getInputStream(), path1);
File targetFile = new File(saveFile, fileNameDb);
Files.copy(file.getInputStream(), targetFile.toPath(),                 StandardCopyOption.REPLACE_EXISTING);
//	Files.copy(file.getInputStream(),Paths.get(fileStoragePath));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileNameDb;
}
}

error when the method is called is :-


java.io.FileNotFoundException: class path resource [static] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:226) ~[spring-core-6.0.9.jar:6.0.9]
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:169) ~[spring-core-6.0.9.jar:6.0.9]
at com.eventhub.service.impl.FileServiceImpl.uploadFile(FileServiceImpl.java:55) ~[classes/:na]
at com.eventhub.service.impl.EventServiceImpl.createEvent(EventServiceImpl.java:75) ~[classes/:na]
at com.eventhub.controllers.EventController.addEvent(EventController.java:79) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) ~[spring-web-6.0.9.jar:6.0.9]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) ~[spring-web-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011) ~[spring-webmvc-6.0.9.jar:6.0.9]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914) ~[spring-webmvc-6.0.9.jar:6.0.9]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590) ~[tomcat-embed-core-10.1.8.jar:6.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.0.9.jar:6.0.9]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.8.jar:6.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.9.jar:6.0.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.9.jar:6.0.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.9.jar:6.0.9]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:166) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:894) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1741) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
at java.base/java.lang.Thread.run(Thread.java:833) ~[na:na][2m2023-06-14T21:16:27.103+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36minMXBeanRegistrar$SpringApplicationAdmin[0;39m [2m:[0;39m Application shutdown requested.
[2m2023-06-14T21:16:27.168+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36mo.apache.catalina.core.StandardService  [0;39m [2m:[0;39m Stopping service [Tomcat]
[2m2023-06-14T21:16:27.172+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36mo.a.c.c.C.[Tomcat].[localhost].[/]      [0;39m [2m:[0;39m Destroying Spring FrameworkServlet 'dispatcherServlet'
[2m2023-06-14T21:16:27.208+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36mj.LocalContainerEntityManagerFactoryBean[0;39m [2m:[0;39m Closing JPA EntityManagerFactory for persistence unit 'default'
[2m2023-06-14T21:16:27.225+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36mcom.zaxxer.hikari.HikariDataSource      [0;39m [2m:[0;39m eventhub - Shutdown initiated...
[2m2023-06-14T21:16:27.286+05:30[0;39m [32m INFO[0;39m [35m24976[0;39m [2m---[0;39m [2m[n(41)-127.0.0.1][0;39m [36mcom.zaxxer.hikari.HikariDataSource      [0;39m [2m:[0;39m eventhub - Shutdown completed.

when i tried Resource resource = new ClassPathResource(""); use this the image gets uploaded under img folder which is created under the target folder .

Resource resource = new ClassPathResource("static/");
Resource resource = new ClassPathResource("/static");

these also didnt work

答案1

得分: 1

尝试在源项目的资源目录中保存文件是错误的。例如,如果应用程序以.war或.jar文件部署,资源目录在执行时甚至可能不存在。资源目录仅在构建应用程序时才预期存在,而在执行时不应存在。您需要配置一个与应用程序分开的目录来上传文件。

英文:

It is an error to try to save files in the resource directory of the source project. It may not even exist at execution time, for example if the application is deployed as a .war or .jar file. The resources directories are only expected to exist only when building the application, not when executing. You need to configure a directory separated from the application to upload files.

huangapple
  • 本文由 发表于 2023年6月15日 00:01:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475495.html
匿名

发表评论

匿名网友

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

确定