Java 如何使用SpringMVC将文件上载到项目目录?

Java 如何使用SpringMVC将文件上载到项目目录?,java,eclipse,spring,spring-mvc,file-upload,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

我需要在我的项目中将图像上传到目录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>

smtp
真的
真的
/WEB-INF/views/
.jsp

保存文件时添加目录:

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

您应该使用servlet上下文来获取绝对路径,因为java.io不知道它正在运行的上下文。试试下面的选项,让我知道它是否有效。另外,请注意,当您重新部署应用程序时,您的图像将被删除。我希望你能意识到这一点

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

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

thanx的答案,但它给了我一个异常,这个catch工作
catch(exception e){System.out.println(“上传失败”);返回“重定向:/user”}
什么样的异常?
java.io.FileNotFoundException:webapp/resources/avatars/myw3schoolsimage.jpg
您需要尝试不同的路径->我指定了相对路径,您需要指定您的路径或使用绝对路径。例如:resources/avatars/或/resources/avatars/。试试看,没什么用。还尝试使用此路径
src/main/webapp/resources/avatars
。没有结果。同样的例外情况:(thanx是一个答案,但它保存了名为avatars+filename的文件。
/home/acid_serg/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/ViolenceAndHate/resources/avatarsiwankqjgq.jpg
smth类似于此使用文件构造函数
文件(字符串路径名)
只需设置路径。对于一组全面的文件构造函数和api,请查看javadoc中的文件。我修复了它。它将我下载到avatars文件夹。但是id不显示(在eclipse中)上载到
/resource/avatars
文件夹的文件。这正常吗?