无法在应用程序路径中存储图像Spring mvc(java.io.FileNotFoundException)

时间:2018-05-24 17:14:58

标签: spring-mvc

在春天mvc我想将图像存储到images folderresources

里面

我尝试使用以下代码

BufferedImage image = null;
        byte[] imageByte;

        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(studentDetails.getStuImg());
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        image = ImageIO.read(bis);
        bis.close();

        String file=    request.getContextPath()+"/resources/images/imageee.png";

        // write the image to a file
        File outputfile = new File(file);  
        ImageIO.write(image, "png", outputfile);

但我得到了以下异常

java.io.FileNotFoundException: \campasAdmin\resources\images\imageee.png (The system cannot find the path specified)
    at java.io.RandomAccessFile.open0(Native Method)
    at java.io.RandomAccessFile.open(Unknown Source)
    at java.io.RandomAccessFile.<init>(Unknown Source)
    at javax.imageio.stream.FileImageOutputStream.<init>(Unknown Source)
    at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(Unknown Source)
    at javax.imageio.ImageIO.createImageOutputStream(Unknown Source)
    at javax.imageio.ImageIO.write(Unknown Source)
    at com.rasvek.cms.controller.StudentController.addfeeCategory(StudentController.java:272)
    at com.rasvek.cms.controller.StudentController$$FastClassBySpringCGLIB$$cb2af793.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:738)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke(MethodBeforeAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke(AfterReturningAdviceInterceptor.java:52)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:673)
    at com.rasvek.cms.controller.StudentController$$EnhancerBySpringCGLIB$$4b76b9e3.addfeeCategory(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

如何存储到以下位置

please look at derectory

我想在上面的位置。 该怎么做,请帮帮我。谢谢!。

2 个答案:

答案 0 :(得分:0)

始终尝试使用通用解决方案,因为路径因操作系统而异。

使用java分隔符,这样无论操作系统(linux / windows)如何,它都能正常工作。

File.separator (import java.io.File;)

如果操作系统 windows ,则在您的情况下,请参阅下面的代码。

尝试替换此行: String file = request.getContextPath()+&#34; /resources/images/imageee.png" ;;

有了这个: String file = request.getContextPath()+&#34; \\resources\\images\\imageee.png&#34 ;;

如果您想将图像存储在tomcat(catalina_home)位置,请参阅以下代码。

String catalinaRootPath = System.getProperty("catalina.home");
File dir = new File(catalinaRootPath + File.separator + "images");
if (!dir.exists()){
    dir.mkdirs();
}

然后在其中写入图像,或者也可以创建子目录然后写入。

答案 1 :(得分:0)

如果我是你,我会使用Spring Content。然后,您不必担心如何实现任何此代码,并且您在存储图像的位置方面具有更大的灵活性。

添加到您的应用程序非常容易。

  

的pom.xml

    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-fs</artifactId>
        <version>0.0.11</version>
    </dependency>
  

StoreConfig.java

@Configuration
@EnableFilesystemStores
public class EnableFilesystemStoresConfig {

    @Bean
    File filesystemRoot() {
        try {
            return new File("/path/to/your/images");
        } catch (IOException ioe) {}
        return null;
    }

    @Bean
    FileSystemResourceLoader fileSystemResourceLoader() {
        return new FileSystemResourceLoader(filesystemRoot().getAbsolutePath());
    }

}
  

ImageStore.java

  public interface ImageStore extends Store<String> {
  }

那就是它。 ImageStore本质上是一个Spring ResourceLoader,因此您需要做的就是自动连接它以使用它。 spring-content-fs依赖项将导致Spring Content代表您注入基于文件系统的实现:

  

ImageStoreTest.java

@RunWith(...)
public class ImageStoreTest {

    @Autowired
    private DocumentStore store;

    @Test
    public void sample() {
       InputStream is = getImageStream();
       Resource r = store.getResource("/some-image.jpg");
       OutputStream os = ((WritableResource)r).getOutputStream();
       IOUtils.copy(is, os);
       is.close();
       os.close();
    }

    public InputStream getImageStream() {
       ...
    }
}

如果要将图像存储在数据库中,或者存储在S3中,那么您只需将依赖项更改为所需的依赖项,并更新@Configuration以添加该特定类型的连接详细信息存储。参考指南位于this page的底部。

当你使用spring web-mvc时,我假设你有一个REST API,所以你可以更进一步。添加此依赖项:

    <dependency>
        <groupId>com.github.paulcwarren</groupId>
        <artifactId>spring-content-rest</artifactId>
        <version>0.0.11</version>
    </dependency>

这个@Import到你的StoreConfig.java:

@Configuration
@EnableFilesystemStores
@Import(RestConfiguration.class)
public class EnableFilesystemStoresConfig {

此ImageStore的@StoreRestResource注释。

  

ImageStore.java

  @StoreRestResource(path="images")
  public interface ImageStore extends Store<String> {
  }

现在,您将在/images拥有一个功能齐全的(POST,PUT,GET,DELETE)基于REST的图像服务,该服务将使用您的ImageStore将您的图像存储在/path/to/your/images中。

因此...

curl --upload-file example-image.jpg /images/example-image.jpg

将上传example-image.jpg并将其存储在服务器上的/path/to/your/images/example-image.jpg中:

GET /images/example-image.jpg

将返回下载它。

HTH