ssm(四)-----文件上传

pom.xml导入下面依赖包

<!--springIoc的依赖包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <!--springMVC的依赖包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.1.RELEASE</version>
    </dependency>
    <!--spring-jdbc的依赖包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.1.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
      <scope>provided</scope>
    </dependency>

    <!--上传下载依赖包-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
    <resources>
          <resource>
              <directory>src/main/java</directory>
              <includes>
                  <include>**/*.xml</include>
              </includes>
          </resource>
      </resources>

web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <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:applicationContext.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings><!--控制台可以输出sql语句-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
</configuration>

applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
       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
       ">

        <!--IOC注解-->
        <context:annotation-config/>
        <context:component-scan base-package="controller"/>
        <!--MVC注解-->
        <mvc:annotation-driven/>

        <!--上传下载-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <property name="maxUploadSize" value="20240000"/><!--总上传大小-->
                <property name="maxInMemorySize" value="10240000"/><!--单个文件上传大小-->
                <property name="defaultEncoding" value="utf-8"/><!--设置编码集-->
        </bean>
</beans>

FileUploadController.java

@Controller
@RequestMapping("/file")
public class FileUploadController {
    @RequestMapping("/upload1")
    public void upload1(@RequestParam("file") CommonsMultipartFile file){
        long start = System.currentTimeMillis();
        String parent = "F:/图片";
        String fileName = new Date().getTime()+"";//得到时间,用于唯一确定文件
        String type = file.getOriginalFilename();//得到文件的后缀
        File desc = new File(parent,fileName+type);
        try{
            InputStream in = file.getInputStream();
            OutputStream os = new FileOutputStream(desc);
            int len = 0;
            while((len = in.read())!= -1){
                os.write(len);
            }
        }catch(Exception e){
            System.out.println(e.getMessage());
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start)/3600);
    }

    @RequestMapping("/upload2")
    public void upload2(@RequestParam("file") CommonsMultipartFile file){
        long start = System.currentTimeMillis();
        String parent = "F:/图片";
        String fileName = new Date().getTime()+"";//得到时间,用于唯一确定文件
        String type = file.getOriginalFilename();//得到文件的后缀
        File desc = new File(parent,fileName+type);
        try {
            file.transferTo(desc);//将file复制到desc
        } catch (IOException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println((end-start)/3600);
    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="file/upload1.do" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <button>上传</button>
    </form>

    <form action="file/upload2.do" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <button>上传</button>
    </form>
</body>
</html>

Demo:带图片的注册
StuInfo.java

public class StuInfo {
    private Integer stuId;
    private String stuName;
    private Integer stuAge;
    private String stuImg;

    public StuInfo() {
    }

    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public Integer getStuAge() {
        return stuAge;
    }

    public void setStuAge(Integer stuAge) {
        this.stuAge = stuAge;
    }

    public String getStuImg() {
        return stuImg;
    }

    public void setStuImg(String stuImg) {
        this.stuImg = stuImg;
    }

    @Override
    public String toString() {
        return "StuInfo{" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuAge=" + stuAge +
                ", stuImg='" + stuImg + '\'' +
                '}';
    }
}

StuMapper.java

public interface StuMapper {
    void saveStu(StuInfo si);
}

StuMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.StuMapper">
    <insert id="saveStu" parameterType="bean.StuInfo">
        insert into stuinfo values(null,#{stuName},#{stuAge},#{stuImg})
    </insert>
</mapper>

StuBiz.java

public interface StuBiz {
    void saveStu(StuInfo si);
}

StuBizImpl.java

@Repository
public class StuBizImpl implements StuBiz {
    @Autowired
    private StuMapper sm;

    @Override
    public void saveStu(StuInfo si) {
        sm.saveStu(si);
    }
}

StuController.java

@Controller
@RequestMapping("/stu")
public class StuController {
    @Autowired
    private StuBiz sb;

    @RequestMapping("/savestu")
    //使用@RequestParam注解将请求参数绑定至方法参数
    /*
    本质区别:MultipartFile 是接口, CommonsMultipartFile 是其实现类
    使用区别:CommonsMultipartFile 类型需要添加@RequestParam
     */
    public String saveStu(StuInfo si,@RequestParam("img") CommonsMultipartFile file){
        String fileType = new Date().getTime()+file.getOriginalFilename();
        si.setStuImg(fileType);
        sb.saveStu(si);
        try {
            file.transferTo(new File("F:/图片",fileType));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }
}

applicationContext.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:mvc="http://www.springframework.org/schema/mvc"
       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
       ">

        <!--IOC注解-->
        <context:annotation-config/>
        <context:component-scan base-package="biz,controller"/>

        <!--MVC注解-->
        <mvc:annotation-driven/>

        <!--配置数据源-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
                <property name="username" value="root"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db1?characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=UTC"/>
                <property name="password" value="root"/>
        </bean>

        <!--创建会话工厂-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
                <property name="dataSource" ref="dataSource"/>
                <property name="configLocation" value="classpath:config.xml"/>
        </bean>

        <!--创建mapper的代理-->
        <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
                <property name="basePackage" value="mapper"/>
        </bean>

        <!--上传下载-->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
                <property name="maxUploadSize" value="20240000"/><!--总上传大小-->
                <property name="maxInMemorySize" value="10240000"/><!--单个文件上传大小-->
                <property name="defaultEncoding" value="utf-8"/><!--设置编码集-->
        </bean>
</beans>

config.xml、web,xml同上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值