【问题标题】:How to upload file to a project directory using Spring MVC?如何使用 Spring MVC 将文件上传到项目目录?
【发布时间】:2016-04-07 12:56:11
【问题描述】:

我需要将图片上传到我的项目 webapp/resources/avatars 中的目录。它将我上传到我的 eclipse 目录。我需要做的是它将图像上传到项目目录并在部署我的项目之后!请帮忙! 这是我上传文件的控制器方法:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String postAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request)
{ 
    if(file.isEmpty())
    {
        return "redirect:/user";
    }
    System.out.println(file.getOriginalFilename());
    String name=file.getOriginalFilename();
    if (!file.isEmpty()) {
        try {           
            byte[] bytes = file.getBytes();
            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(name)));
            stream.write(bytes);
            stream.close();

            System.out.println("You have uploaded file");
        } catch (Exception e) {
          System.out.println("Failed to upload");
          return "redirect:/user";
        }
    }
    return"user";
}

这是我的 dispatcher-servlet.xml 文件

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd 
    http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd


     "
    xmlns:tx="http://www.springframework.org/schema/tx">


    <context:component-scan base-package="
    com.vandh.app " />


    <context:property-placeholder location="classpath:database.properties" />
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:resources mapping="/avatars/**" location="file:/resources/avatars"/>
    <mvc:annotation-driven />
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
    </bean>

                    <!-- Mail Sending properties -->
    <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl">
        <property name="host" value="smtp.gmail.com" />
        <property name="port" value="587" />
        <property name="username" value="violandhate@gmail.com" />
        <property name="password" value="violenceandhate" />
        <property name="javaMailProperties">
            <props>
                <prop key="mail.transport.protocol">smtp</prop>
                <prop key="mail.smtp.auth">true</prop>
                <prop key="mail.smtp.starttls.enable">true</prop>
            </props>
        </property>
    </bean>

        <bean id="multipartResolver"
   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5000000"/>
</bean>

    <tx:annotation-driven/>     
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="persistenceExceptionTranslationPostProcessor"
        class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">



        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
</beans>

【问题讨论】:

    标签: java eclipse spring spring-mvc file-upload


    【解决方案1】:

    您应该使用 servlet 上下文来获取绝对路径,因为 java.io 不知道它正在运行的上下文。尝试使用以下选项,让我知道它是否有效。还要在这里做一个说明,当您重新部署应用程序时,您的图像将被删除。我希望你知道它..

    @Autowired
        ServletContext context;
    ............
    
    String relativeWebPath = "/resources/avatars";
    String absoluteFilePath = context.getRealPath(relativeWebPath);
    File uploadedFile = new File(absoluteFilePath, "your file name");
    

    【讨论】:

    • 感谢答案,但它为我保存了名为 avatars+filename 的文件。 /home/acid_serg/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ViolenceAndHate/resources/avatarsiWankqCQJgQ.jpg 那样的东西
    • 使用文件构造函数File(String pathname) 来设置路径。有关完整的文件构造函数和 api 集,请查看 javadoc for File。
    • 我修好了。它将我下载到头像文件夹。但 id 不显示(在 Eclipse 中)上传到 /resource/avatars 文件夹的文件。正常吗?
    【解决方案2】:

    保存文件时添加目录:

    BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File("your_path" + name)));
    

    【讨论】:

    • thanx 的答案,但它给了我一个例外,这个捕获工作 catch (Exception e) { System.out.println("Failed to upload"); return "redirect:/user"; }
    • 什么样的异常?
    • java.io.FileNotFoundException: webapp/resources/avatars/myw3schoolsimage.jpg
    • 你需要尝试不同的路径 -> 我指定了相对路径,你需要指定你的或使用绝对路径。例如:resources/avatars/ 或 /resources/avatars/。试试看。
    • 没有任何帮助。还尝试使用此路径src/main/webapp/resources/avatars。没有结果。同样的例外:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多