springmvc的文件上传和下载


前言

本篇文章主要介绍ssm框架中springmvc的文件上传和下载,上传就是将需要的文件上传到指定目录并将文件信息保存到数据库,下载即到指定目录下载已上传的文件


提示:以下是本篇文章正文内容,下面案例可供参考

一、添加相关配置

1、在pom.xml中添加文件上传相关依赖

 <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
  </dependency>

2、配置文件上传解析器(CommonsMultipartResolver),加在spring-mvc.xml配置文件中的最后(默认是叫springmvc-servlet.xml)

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

二、相关代码

1、参考的数据库表t_file

create table t_file
(
  file_id varchar(32) primary key,
  real_name varchar(50) not null,
  content_type varchar(50) not null,
  url varchar(256) not null,
  update_datetime timestamp NULL default CURRENT_TIMESTAMP    -- insert=false
);

2.实体类File.java

package com.zking.ssm.model;
import lombok.ToString;
import java.util.Date;
@ToString
public class File {
    private String fileId;
    private String realName;
    private String contentType;
    private String url;
    private Date updateDatetime;
    public File(String fileId, String realName, String contentType, String url, Date updateDatetime) {
        this.fileId = fileId;
        this.realName = realName;
        this.contentType = contentType;
        this.url = url;
        this.updateDatetime = updateDatetime;
    }
    public File() {
        super();
    }
    public String getFileId() {
        return fileId;
    }
    public void setFileId(String fileId) {
        this.fileId = fileId;
    }
    public String getRealName() {
        return realName;
    }
    public void setRealName(String realName) {
        this.realName = realName;
    }
    public String getContentType() {
        return contentType;
    }
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public Date getUpdateDatetime() {
        return updateDatetime;
    }
    public void setUpdateDatetime(Date updateDatetime) {
        this.updateDatetime = updateDatetime;
    }
}

3.DAO层FileMapper.java(这里上传主要用到了insert方法)

package com.zking.ssm.mapper;
import com.zking.ssm.model.File;
import org.springframework.stereotype.Repository;
@Repository
public interface FileMapper {
    int deleteByPrimaryKey(String fileId);
    int insert(File record);
    int insertSelective(File record);
    File selectByPrimaryKey(String fileId);
    int updateByPrimaryKeySelective(File record);
    int updateByPrimaryKey(File record);
}

4.DAO层映射文件FileMapper.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="com.zking.ssm.mapper.FileMapper" >
  <resultMap id="BaseResultMap" type="com.zking.ssm.model.File" >
    <constructor >
      <idArg column="file_id" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="real_name" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="content_type" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="url" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="update_datetime" jdbcType="TIMESTAMP" javaType="java.util.Date" />
    </constructor>
  </resultMap>
  <sql id="Base_Column_List" >
    file_id, real_name, content_type, url, update_datetime
  </sql>
  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    from t_file
    where file_id = #{fileId,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from t_file
    where file_id = #{fileId,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.zking.ssm.model.File" >
    insert into t_file (file_id, real_name, content_type, 
      url)
    values (#{fileId,jdbcType=VARCHAR}, #{realName,jdbcType=VARCHAR}, #{contentType,jdbcType=VARCHAR}, 
      #{url,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.zking.ssm.model.File" >
    insert into t_file
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="fileId != null" >
        file_id,
      </if>
      <if test="realName != null" >
        real_name,
      </if>
      <if test="contentType != null" >
        content_type,
      </if>
      <if test="url != null" >
        url,
      </if>
      <if test="updateDatetime != null" >
        update_datetime,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="fileId != null" >
        #{fileId,jdbcType=VARCHAR},
      </if>
      <if test="realName != null" >
        #{realName,jdbcType=VARCHAR},
      </if>
      <if test="contentType != null" >
        #{contentType,jdbcType=VARCHAR},
      </if>
      <if test="url != null" >
        #{url,jdbcType=VARCHAR},
      </if>
      <if test="updateDatetime != null" >
        #{updateDatetime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zking.ssm.model.File" >
    update t_file
    <set >
      <if test="realName != null" >
        real_name = #{realName,jdbcType=VARCHAR},
      </if>
      <if test="contentType != null" >
        content_type = #{contentType,jdbcType=VARCHAR},
      </if>
      <if test="url != null" >
        url = #{url,jdbcType=VARCHAR},
      </if>
      <if test="updateDatetime != null" >
        update_datetime = #{updateDatetime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where file_id = #{fileId,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zking.ssm.model.File" >
    update t_file
    set real_name = #{realName,jdbcType=VARCHAR},
      content_type = #{contentType,jdbcType=VARCHAR},
      url = #{url,jdbcType=VARCHAR},
      update_datetime = #{updateDatetime,jdbcType=TIMESTAMP}
    where file_id = #{fileId,jdbcType=VARCHAR}
  </update>
</mapper>  

5.service层接口IFileService.java

package com.zking.ssm.service;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface IFileService {
    /**
     * 文件上传
     * @param file  文件对象
     */
    void add(com.zking.ssm.model.File file);
    /**
     * 查询所有文件
     * @param fileId 文件id
     * @return  文件对象
     */
    com.zking.ssm.model.File load(String fileId);
}

6.service层接口实现类FileServiceImpl.java

package com.zking.ssm.service.impl;
import com.zking.ssm.mapper.FileMapper;
import com.zking.ssm.model.File;
import com.zking.ssm.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * @ClassName FileServiceImpl
 * @Description TODO
 * @Author Yan
 * @Date 2021-10-14 17:39
 **/
@Service
public class FileServiceImpl implements IFileService {
    @Autowired
    private FileMapper fileMapper;
    @Override
    public void add(File file) {
        fileMapper.insert(file);
    }
    @Override
    public File load(String fileId) {
        return fileMapper.selectByPrimaryKey(fileId);
    }
}

7.junit测试公用类BaseTestCace.java

package com.zking.ssm.service.impl;
import com.zking.ssm.util.PageBean;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * @ClassName BaseTestCase
 * @Description TODO
 * @Author Yan
 * @Date 2021-10-08 21:33
 **/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring.xml"})
public class BaseTestCase {
    protected PageBean pageBean;
    @Before
    public void setUp() throws Exception {
        pageBean=new PageBean();
    }
}

8.service层接口实现类junit测试类FileServiceImplTest.java

package com.zking.ssm.service.impl;
import com.fasterxml.jackson.databind.Module;
import com.zking.ssm.model.File;
import com.zking.ssm.service.IFileService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.UUID;
import static org.junit.Assert.*;
public class FileServiceImplTest extends BaseTestCase {
    @Autowired
    private IFileService fileService;
    private com.zking.ssm.model.File file;
    @Override
    public void setUp() throws Exception {
        super.setUp();
        file=new File();
    }
    @Test
    public void add() {
        String fileId=UUID.randomUUID().toString().replace("-","");
        String realName="aaff.jpg";
        String str=realName.substring(realName.lastIndexOf("."));
        String contentType="jpg/png/image";
        String url="E:\\temp\\uploads\\"+System.currentTimeMillis()+str;

        file.setFileId(fileId);
        file.setRealName(realName);
        file.setContentType(contentType);
        file.setUrl(url);
        fileService.add(file);
    }

    @Test
    public void load() {
        file.setFileId("6201e5fbf89043f58fde090775bb6be6");
        File load = fileService.load(file.getFileId());
        System.out.println(load);
    }
}

9.控制层FileController.java

package com.zking.ssm.controller;
import com.zking.ssm.model.File;
import com.zking.ssm.service.IFileService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
//import java.io.File;
import java.util.UUID;
/**
 * @ClassName FileController
 * @Description TODO
 * @Author Yan
 * @Date 2021-10-14 18:05
 **/
@Controller
@RequestMapping("/file")
public class FileController {

    @Autowired
    private IFileService fileService;

    @RequestMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }


    @RequestMapping("/upload")
    public String upload(MultipartFile img, ModelMap model) throws Exception{
     //1.将文件信息保存到数据库
        //设置文件id
        String fileId= UUID.randomUUID().toString().replace("-","");
        //获取到上传文件的真实文件名
        String realName=img.getOriginalFilename();
        //截取到真实文件名的后缀名,并且使用时间戳重命名新文件组成最后上传文件的文件名
        String str=System.currentTimeMillis()+realName.substring(realName.lastIndexOf("."));
        //获取到文件的类型
        String contentType=img.getContentType();
        //设置上传文件的上传路径
        String url="E:\\temp\\uploads\\"+str;

        //实例化文件对象,将文件信息保存到数据库
        com.zking.ssm.model.File file=new File();
        file.setFileId(fileId);
        file.setRealName(realName);
        file.setContentType(contentType);
        file.setUrl(url);
        fileService.add(file);

     //2.将文件写入到文件服务器
        java.io.File targetFile=new java.io.File(url);
        img.transferTo(targetFile);

        //将上传的文件路径、真实文件名和文件名存到作用域
        model.put("url",url);
        model.put("realName",realName);
        model.put("str",str);
        return "success";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request, @RequestParam String fileName, Model model) throws Exception {

        //下载文件路径
        String realPath ="E:\\temp\\uploads\\";
        //创建文件对象
        java.io.File file = new java.io.File(realPath+ java.io.File.separator+fileName);

        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //解决中文乱码问题
        String downloadFileName = new String(fileName.getBytes(),"ISO-8859-1");
        //通知浏览器下载文件
        headers.setContentDispositionFormData("attachment",downloadFileName);
        //以二进制文件流的形式下载文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //返回封装后的下载数据
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
    }
}

10.视图层index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="/common/head.jsp"></jsp:include>
</head>
<body>
    <div>
        <a href="${ctx}/file/toUpload">图片上传</a>
    </div>
</body>
</html>

11.视图层upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <jsp:include page="/common/head.jsp"></jsp:include>
</head>
<body>
    <h1>文件上传</h1>
    <form action="${ctx}/file/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="img">
        <input type="submit" value="上传">
    </form>
</body>
</html>

12.视图层success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <jsp:include page="/common/head.jsp"></jsp:include>
    <title>文件上传成功</title>
</head>
<body>
<h1>文件上传成功!</h1>
真实文件名${realName}<br>
文件路径${url}<br>
加时间戳的文件名${str}<br>
<a href="${ctx}/file/download?fileName=${str}">${str}下载</a>
</body>
</html>

13.效果图参考

请添加图片描述

总结

以上就是今天要讲的内容,本文简单介绍了springMVC中文件上传和下载的使用,需要注意的是表单提交方式为method="post" enctype="multipart/form-data",文件项需要用spring提供的MultipartFile进行接收
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

内心留白的阿舒

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值