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

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

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());

  1. package com.eventhub.service.impl;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.StandardCopyOption;
  6. import java.util.UUID;
  7. import org.springframework.core.io.ClassPathResource;
  8. import org.springframework.core.io.Resource;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import com.eventhub.service.FileService;
  12. @Service
  13. public class FileServiceImpl implements FileService {
  14. @Override
  15. public String uploadFile(MultipartFile file) throws IOException {
  16. // getting file name
  17. String fileName = file.getOriginalFilename();
  18. // Create a random name for our file to be stored in the db
  19. String randomId = UUID.randomUUID().toString();
  20. // adding the extension of our uploaded file
  21. String fileNameDb = randomId.concat(fileName.substring(fileName.lastIndexOf(".")));
  22. // full storage path
  23. // String fileStoragePath = path + File.separator + fileNameDb;
  24. // creating the storage folder if it doesn't exist (for now img )
  25. // File f = new File(path);
  26. // File saveFile = new ClassPathResource("static/img").getFile();
  27. Resource resource = new ClassPathResource("static");
  28. File staticDir = resource.getFile();
  29. System.out.println(staticDir);
  30. File saveFile = new File(staticDir, "img");
  31. if (!saveFile.exists()) {
  32. saveFile.mkdirs();
  33. }
  34. // copying the file in our folder / directory
  35. try {
  36. // Path path1 = Paths.get(saveFile.getAbsolutePath() + File.separator + fileNameDb);
  37. // Files.copy(file.getInputStream(), path1);
  38. File targetFile = new File(saveFile, fileNameDb);
  39. Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
  40. // Files.copy(file.getInputStream(),Paths.get(fileStoragePath));
  41. } catch (IOException e) {
  42. // TODO Auto-generated catch block
  43. e.printStackTrace();
  44. }
  45. return fileNameDb;
  46. }
  47. }

Error when the method is called is:

  1. 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());

  1. package com.eventhub.service.impl;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.StandardCopyOption;
  6. import java.util.UUID;
  7. import org.springframework.core.io.ClassPathResource;
  8. import org.springframework.core.io.Resource;
  9. import org.springframework.stereotype.Service;
  10. import org.springframework.web.multipart.MultipartFile;
  11. import com.eventhub.service.FileService;
  12. @Service
  13. public class FileServiceImpl implements FileService{
  14. @Override
  15. public String uploadFile(MultipartFile file) throws IOException {
  16. // getting file name
  17. String fileName = file.getOriginalFilename();
  18. // Create a random name for our file to be stored in the db
  19. String randomId = UUID.randomUUID().toString();
  20. // adding the extension of our uploaded file
  21. String fileNameDb = randomId.concat(fileName.substring(fileName.lastIndexOf(".")));
  22. // full storage path
  23. //String fileStoragePath = path + File.separator + fileNameDb;
  24. //creating the storage folder if it doesn't exists (for now img )
  25. // File f = new File(path);
  26. // File saveFile = new ClassPathResource("static/img").getFile();
  27. Resource resource = new ClassPathResource("static");
  28. File staticDir = resource.getFile();
  29. System.out.println(staticDir);
  30. File saveFile = new File(staticDir, "img");
  31. if(!saveFile.exists()) {
  32. saveFile.mkdirs();
  33. }
  34. // coping the file in our folder / directory
  35. try {
  36. // Path path1 = Paths.get(saveFile.getAbsolutePath() + File.separator + fileNameDb);
  37. //
  38. // Files.copy(file.getInputStream(), path1);
  39. File targetFile = new File(saveFile, fileNameDb);
  40. Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
  41. // Files.copy(file.getInputStream(),Paths.get(fileStoragePath));
  42. } catch (IOException e) {
  43. // TODO Auto-generated catch block
  44. e.printStackTrace();
  45. }
  46. return fileNameDb;
  47. }
  48. }

error when the method is called is :-

  1. java.io.FileNotFoundException: class path resource [static] cannot be resolved to URL because it does not exist
  2. at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:226) ~[spring-core-6.0.9.jar:6.0.9]
  3. at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:169) ~[spring-core-6.0.9.jar:6.0.9]
  4. at com.eventhub.service.impl.FileServiceImpl.uploadFile(FileServiceImpl.java:55) ~[classes/:na]
  5. at com.eventhub.service.impl.EventServiceImpl.createEvent(EventServiceImpl.java:75) ~[classes/:na]
  6. at com.eventhub.controllers.EventController.addEvent(EventController.java:79) ~[classes/:na]
  7. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
  8. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77) ~[na:na]
  9. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
  10. at java.base/java.lang.reflect.Method.invoke(Method.java:568) ~[na:na]
  11. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:207) ~[spring-web-6.0.9.jar:6.0.9]
  12. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:152) ~[spring-web-6.0.9.jar:6.0.9]
  13. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:118) ~[spring-webmvc-6.0.9.jar:6.0.9]
  14. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:884) ~[spring-webmvc-6.0.9.jar:6.0.9]
  15. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) ~[spring-webmvc-6.0.9.jar:6.0.9]
  16. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-6.0.9.jar:6.0.9]
  17. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1081) ~[spring-webmvc-6.0.9.jar:6.0.9]
  18. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:974) ~[spring-webmvc-6.0.9.jar:6.0.9]
  19. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1011) ~[spring-webmvc-6.0.9.jar:6.0.9]
  20. at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:914) ~[spring-webmvc-6.0.9.jar:6.0.9]
  21. at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:590) ~[tomcat-embed-core-10.1.8.jar:6.0]
  22. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) ~[spring-webmvc-6.0.9.jar:6.0.9]
  23. at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) ~[tomcat-embed-core-10.1.8.jar:6.0]
  24. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  25. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  26. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) ~[tomcat-embed-websocket-10.1.8.jar:10.1.8]
  27. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  28. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  29. at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-6.0.9.jar:6.0.9]
  30. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
  31. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  32. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  33. at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-6.0.9.jar:6.0.9]
  34. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
  35. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  36. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  37. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-6.0.9.jar:6.0.9]
  38. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[spring-web-6.0.9.jar:6.0.9]
  39. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  40. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  41. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:166) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  42. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  43. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  44. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  45. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  46. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  47. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:341) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  48. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  49. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  50. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:894) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  51. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1741) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  52. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  53. at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  54. at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  55. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-10.1.8.jar:10.1.8]
  56. 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.
  57. [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]
  58. [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'
  59. [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'
  60. [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...
  61. [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:

确定