Serg Shapoval
Serg Shapoval

Reputation: 717

How to upload file to a project directory using Spring MVC?

I need to upload image to dir in my project webapp/resources/avatars. It uploads me to my eclipse dir. What i need to do that it would upload images to project dir and after deploying my project! Help pls! Here is my controller method for uploading files:

@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";
}

This is my dispatcher-servlet.xml file

    <?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="[email protected]" />
        <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>

Upvotes: 2

Views: 7310

Answers (2)

minion
minion

Reputation: 4353

You should be using servlet context to get the absolute path as java.io is not aware of the context it is running. Try with the below option and let me know if it works. Also to make a note here, your images will be deleted when you redeploy the application. I hope you are aware of it..

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

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

Upvotes: 3

m.aibin
m.aibin

Reputation: 3593

Add directory when you save file:

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

Upvotes: 0

Related Questions