Spring MVC上传

强烈推荐一个大神的人工智能的教程:http://www.captainbed.net/zhanghan

简述

项目中上传和下载是非常常见的功能,如果项目中使用的是Spring MVC,那么实现上传和下载真是很简单咯。

上传

1.添加相关jar包的依赖

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.7.RELEASE</version>
</dependency>
<!-- fileupload-->
<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
</dependency>
<!-- servlet-api -->
<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
</dependency>

jar包引用说明:
使用jsp需要配置视图解析器,上传功能需要配置上传文件解析器,因此需要引用spring-webmvc的jar包,上传文件方法的controller使用时要被加载到IOC容器中,因此需要配置包扫描,包扫描在spring-context包下,这个包已经在spring-webmvc下依赖,所以不需要重复依赖。上传是基于commons-fileupload的,因此需要引用commons-fileupload的jar包

2.编写springmvc的配置文件springmvc-config.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--包扫描-->
    <context:component-scan base-package="zh.spring.controller"/>
    <!--注解驱动-->
    <mvc:annotation-driven/>
    <!--上传解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxInMemorySize">
            <value>10485760</value>
        </property>
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="WEB-INF/content/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

3.配置前端控制器

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

    <!--前端控制器-->
    <servlet>
        <servlet-name>FileUpload</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>FileUpload</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

4.添加jsp文件


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <h2>文件上传</h2>

    <form action="upload" enctype="multipart/form-data" method="post">
        <table>
            <tr>
                <td>请选择文件:</td>
                <td><input type="file" name="file"></td>
            </tr>
            <tr>
                <td><input type="submit"value="上传"></td>
            </tr>
        </table>
    </form>
</body>
</html>


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>上传成功</title>
</head>
<body>
    <h2>恭喜你,上传成功了</h2>
</body>
</html>

5.Controller方法

package zh.spring.controller;

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.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;


@Controller
public class FileUploadController {
    @RequestMapping("index")
    public String index(){
        return "uploadForm";
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public String upload(HttpServletRequest request,
                         @RequestParam("file")MultipartFile file) throws Exception{
        if(!file.isEmpty()){
//            上传文件路径
            String path = request.getServletContext().getRealPath("/images/");
            System.out.println(path);
//            上传文件名
            String filename = file.getOriginalFilename();
            File filepath = new File(path,filename);
            if(!filepath.getParentFile().exists()){
                filepath.getParentFile().mkdirs();
            }
//            将上传文件保存到一个目标文件中
            file.transferTo(new File(path+File.separator+filename));
            return "success";
        }else{
            return "error";
        }
    }
}

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页