【问题标题】:How to upload image inside webapp folder [duplicate]如何在webapp文件夹中上传图片[重复]
【发布时间】:2014-08-28 14:07:28
【问题描述】:

我正在尝试使用 ServletContext 将图像文件上传到 /webapp/foto/ 上的文件夹照片,但每次我得到 NullPointerExceptions

我怎样才能正确地做到这一点?

这是 NPE 在 CONTAINER_ROOT 变量上上升的 UploadFile.class。

@Component
public class UploadFile {

    @Autowired
    HttpServletRequest httpServletRequest;

    private String CONTAINER_ROOT = httpServletRequest.getSession().getServletContext().getRealPath("/");

    private String DIR_NAME = "foto";

    private String UPLOAD_DIR = CONTAINER_ROOT + File.separator + DIR_NAME;

    private Logger logManager = LogManager.getLogger(this.getClass());


    public String getUploadedPath(MultipartFile file) {
        return upload(file);
    }

    private String upload(MultipartFile file) {

        if (!file.isEmpty()) try {
            byte[] bytes = file.getBytes();
            String fileName = file.getOriginalFilename();
            File dir = new File(UPLOAD_DIR);

            if (!dir.exists()) dir.mkdirs();

            File fileOnServer = new File(dir.getAbsolutePath() + File.separator + fileName);
            BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(fileOnServer));
            outputStream.write(bytes);
            outputStream.close();

            logManager.warn("UPLOADED FILE LOCATION: " + fileOnServer.getAbsolutePath());

            return fileOnServer.getPath();
        }
        catch (IOException e) {
            logManager.error("Error trying to upload file to location, or file is empty!", e.getMessage());
        }
        return null;
    }

}

这就是我在 Controller 上的使用方式:

Foto savedFoto = this.fotoRepository.save(new Foto(this.uploadFile.getUploadedPath(file), savedImovel));

堆栈跟踪:

    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [br.com.agenciadsw.morenoimoveis.util.UploadFile]: Constructor threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:164)
28-Aug-2014 11:02:16.409 WARNING [RMI TCP Connection(2)-127.0.0.1] org.apache.catalina.loader.WebappClassLoader.clearReferencesJdbc The web application [] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1069)
    ... 71 more
Caused by: java.lang.NullPointerException
    at br.com.agenciadsw.morenoimoveis.util.UploadFile.<init>(UploadFile.java:26)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:148)
    ... 73 more

这里是web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
            http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>MorenoImoveis</display-name>


        <servlet>
            <servlet-name>dispacher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextClass</param-name>
                <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
            </init-param>
            <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                br.com.agenciadsw.morenoimoveis.cfg.PersistenceConfigurer
                br.com.agenciadsw.morenoimoveis.cfg.SecurityConfigurer
                br.com.agenciadsw.morenoimoveis.cfg.WebMvcConfigurer
            </param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispacher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </context-param>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            br.com.agenciadsw.morenoimoveis.cfg.PersistenceConfigurer
            br.com.agenciadsw.morenoimoveis.cfg.SecurityConfigurer
            br.com.agenciadsw.morenoimoveis.cfg.WebMvcConfigurer
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

【问题讨论】:

    标签: spring servlets file-upload


    【解决方案1】:

    您可以在项目外的文件夹中上传图片。我对几个图像有用

    try {
                byte[] bytes = file.getBytes();
    
                // Creating the directory to store file
                File dir = new File(Utils.getFolderStoreImage(request.getSession().getServletContext().getRealPath("/")));
                if (!dir.exists())
                    dir.mkdirs();
                // Create the file on server
                serverFile = new File(Utils.getFolderStoreImage(request.getServletContext().getRealPath("/"))+System.currentTimeMillis()+"-"+UUID.randomUUID().toString()+".jpg");
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                stream.write(bytes);
                stream.close();
            } catch (Exception e) {
                result.rejectValue("image", "error when upload image");
                return "product/add";
            }
    

    Utils.java

    public class Utils {
    public static String getFolderStoreImage(String webContentRoot) {
        if (webContentRoot.endsWith("\\")){
            webContentRoot = webContentRoot.substring(0,webContentRoot.length() - 1);
            }
        String folder = webContentRoot.substring(0, webContentRoot.lastIndexOf("\\") + 1) + "upload\\";
        return folder;
    }
    

    }

    【讨论】:

      【解决方案2】:

      Spring 组件的默认作用域是单例,因此 bean 可能在应用程序启动时初始化,此时不存在 servlet 请求。尝试在类中添加以下注解:

      @Scope("request")
      

      你可以找到有效的bean范围here

      【讨论】:

      • 我收到了一条消息Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.@Scope("session") 或@Scope("request")
      • 你使用 Spring DispatcherServlet 吗?如果没有,您必须在 web.xml 中启用 RequestContextListener 或 RequestContextFilter(在此处查找示例:theserverside.com/tutorial/…),否则您的请求或会话范围的 bean 无权访问 Spring ApplicationContext。
      • 是的,我已经声明了,我用完整的 web.xml 编辑了帖子我像教程一样添加了过滤器,但没有任何反应
      【解决方案3】:

      此代码将帮助您上传任意数量的文件。这里MultipartFile是包org.springframework.web.multipart.MultipartFile的接口;

       String uploadsDir = "/uploads/";
                  String realPathtoUploads = request.getSession().getServletContext().getRealPath(uploadsDir);
      
                  if (!new File(realPathtoUploads).exists()) {
                      new File(realPathtoUploads).mkdir();
                  }
      
                  List<MultipartFile> files = upload.getFiles();
      
                  List<String> fileNames = new ArrayList<String>();
                  try {
                      if (files != null && files.size() > 0) {
                          for (MultipartFile file : files) {
                              String fileName = file.getOriginalFilename();
                              String filePath = realPathtoUploads + File.separator + fileName;
      
                              File destination = new File(filePath);
                              file.transferTo(destination);
                              fileNames.add(fileName);
      
      
                          }
                      }
                  } catch (IllegalStateException e) {
                      e.printStackTrace();
                      isSuccess = false;
                      logger.error("Error : ", e);
                  }
      

      【讨论】:

        猜你喜欢
        • 2013-02-14
        • 2017-10-05
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        • 2013-06-26
        相关资源
        最近更新 更多