如何使用Spring MVC将文件上传到项目目录?

时间:2016-01-03 22:14:46

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

我需要在项目 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>

2 个答案:

答案 0 :(得分:3)

您应该使用servlet上下文来获取绝对路径,因为java.io不知道它正在运行的上下文。尝试使用以下选项,让我知道它是否有效。另外,要在此处记下,重新部署应用程序时将删除您的图像。我希望你知道它..

@Autowired
    ServletContext context;
............

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

答案 1 :(得分:0)

保存文件时添加目录:

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