关闭

springMVC文件上传

标签: springmvc上传
575人阅读 评论(0) 收藏 举报

这里只讲解使用springMVC包装好的解析器进行上传

1.下载相关jar包。需要引入的jar出了springMVC的jar包外,还需要引入com.springsource.org.apache.commons.fileupload-1.2.0.jar和com.springsource.org.apache.commons.io-1.4.0.jar。

2.配置springMVC的xml
主要就是配置multipartResolver 不然在上传的时候会报MultipartFile的错误

<?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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <description>Spring MVC Configuration</description>

    <!-- 加载配置属性文件 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath*:/application.properties" />

    <!-- 使用Annotation自动注册Bean,只扫描@Controller -->
    <context:component-scan base-package="com.yihg.api"><!-- base-package 如果多个,用“,”分隔 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 设置请求映射编码,解决@ResponseBody乱码问题 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/plain;charset=UTF-8</value>
                        </list>
                    </property>
                </bean>
                <bean id="jsonConverter"
                         class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                         <property name="supportedMediaTypes" value="application/json" />
                </bean>
            </list>
        </property>
    </bean>


    <!--  启动注解,默认的注解映射的支持,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping -->
     <mvc:annotation-driven/>

    <!-- 对静态资源文件的访问, 将无法mapping到Controller的path交给default servlet handler处理 -->
    <mvc:default-servlet-handler/>


    <!-- 视图文件解析配置 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="${web.view.prefix}"/>
        <property name="suffix" value="${web.view.suffix}"/>
    </bean>

    <!-- 定义无Controller的path<->view直接映射 -->
    <mvc:view-controller path="/" view-name="redirect:${web.view.index}"/>


    <!-- 静态文件(css、js、images)配置不经过DispatchServelet处理 
    <mvc:resources location="/resources/" mapping="/resources/**" />
    -->

    <!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  

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

    <!-- 异常解析器 -->
    <bean id="simpleMappingExceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 方法不支持错误 -->
                <prop
                    key="org.springframework.web.HttpRequestMethodNotSupportedException">common/500</prop>
            </props>
        </property>
    </bean>
</beans>

3 在web.xml中配置加载springMVC

    <!-- SpringMVC -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

4.新建一个jsp页面,测试文件上传(这里测试的是多文件上传,单个文件写一个就可以了,注意多文件上传时name名称要相同) enctype=”multipart/form-data” 将文件已二进制的格式传入后台 必须配置

<html>
<body>
<h2>Hello World!</h2>
<form action="<%=request.getContextPath() %>/userInfo/editPhotos" method="post" enctype="multipart/form-data">
    <input type="file" name="pics"/>
    <input type="file" name="pics"/>
    <input type="file" name="pics"/>
    <input type="file" name="pics"/>
    <input type="submit"/>
</form>
</body>
</html>

5.后台接收上传文件的controller
package com.yihg.api.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.csource.common.MyException;
import org.csource.upload.UploadFileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.rop.response.Response;
import com.yihg.supplier.po.SupplierImg;

@Controller
@RequestMapping(“/userInfo”)
public class UserInfoController {

@ResponseBody
@RequestMapping(value = "/editPhoto", method = {RequestMethod.POST,RequestMethod.GET})
public Response editPhoto(HttpServletRequest request,
        @RequestParam(value = "pics", required = true) MultipartFile pics) throws IOException, MyException {

    String imgUrl = UploadFileUtil.uploadFile(pics.getInputStream(), "jpg",
            null);
    System.out.print(imgUrl);
    Response response = new Response();
    response.getResult().setResult("1");
    response.getResult().setMessage("操作成功");
    return response;
}

@ResponseBody
@RequestMapping(value = "/editPhotos", method = {RequestMethod.POST,RequestMethod.GET})
public Response editPhotos(HttpServletRequest request,
        @RequestParam(value = "pics", required = true) MultipartFile[] pics) throws IOException, MyException {

    for (int i = 0; i < pics.length; i++) {
        MultipartFile f = pics[i];
        String imgUrl = UploadFileUtil.uploadFile(f.getInputStream(), "jpg", null);
        System.out.print(imgUrl);
    }
    Response response = new Response();
    response.getResult().setResult("1");
    response.getResult().setMessage("操作成功");
    return response;
}

}

第一个方法是测试单个文件上传的,第二个方法是测试多文件上传的,至此springMVC上传文件完成

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:44501次
    • 积分:979
    • 等级:
    • 排名:千里之外
    • 原创:44篇
    • 转载:29篇
    • 译文:4篇
    • 评论:8条
    文章分类
    最新评论