SSM 文件上传与下载——(文件上传)

1、介绍

在做项目当中,业务需用到文件上传与下载的功能,为此去学习了下怎么使用,同时结合到 SSM 框架当中去,接下来我把我个人的理解放上来供大家学习下,希望能帮到你们。

  首先,文件的上传与下载主要通过 SpringMVC 中的 MultipartResolver 来实现的,所以要实现功能,就要注册相应的 MultipartResolver 即可:

  MultipartResolver 的实现类有两个:

  1. CommonsMultipartResolver :需要 Apache 的 commons-fileupload 支持,它能在比较旧的 Servlet 版本中使用,兼容性好。
  2. StandardServletMultipartResolver:不需要第三方的 jar 包支持,它使用 Servlet 内置的上传功能,但只能在 Servlet 3 以上的版本中使用。

在本次的例子我们使用 StandardServletMultipartResolver

2、准备工作

首先,在 web.xml 中为 DispatcherServlet 配置 Multipart

<!--配置springMVC容器-->
    <servlet>
        <servlet-name>webs</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-web.xml</param-value>
        </init-param>
        <multipart-config>
            <!--上传文件的大小限制,比如下面表示 5 M-->
            <max-file-size>5242880</max-file-size>
            <!--一次表单提交中文件的大小限制,必须下面代表 10 M -->
            <max-request-size>10485760</max-request-size>
            <!-- 多大的文件会被自动保存到硬盘上。0 代表所有 -->
            <file-size-threshold>0</file-size-threshold>
        </multipart-config>
    </servlet>

然后,在 spring 中注册 Multipart

<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />

到这里后就可以使用了

3、使用

JSP 的页面:
  注意,form 表单记得加上 enctype="multipart/form-data",作用是声明表单中带有文件。

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <title>文件的上传下载</title>
    <body>
        <form action="/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="filename"/><br/><br/>
            <input type="submit" value="提交">
        </form>
        <div>${sessionScope.msg}</div>
    </body>
</html>

后台代码:

package com.zhhy.ljk.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping(path = "/upload")
public class FileUploadController {

    @RequestMapping(path = "", method = RequestMethod.GET)
    public String getPage() {
        return "index";
    }

    @PostMapping
    public String uploadFile(@RequestPart("filename") MultipartFile multipartFile, HttpServletRequest request) {

        HttpSession session = request.getSession();

        // 判断上传的文件是否为空
        if (!multipartFile.isEmpty()) {
            // 验证文件为什么格式并且文件大小不能超过 5MB
            if (multipartFile.getContentType().contains("image/") && multipartFile.getSize() < 1024 * 1024 * 1024 * 5) {
                // 文件的存储位置
                String aa = "D:\\1";
                // 获取上传文件的文件名加后缀名
                String fileName = multipartFile.getOriginalFilename();
                // 截取上传文件的文件名
                String imageName = fileName.substring(0, fileName.indexOf("."));
                // 截取上传文件的后缀名
                String zhui = fileName.substring(fileName.indexOf("."), fileName.length());
                // 设置生成时间格式
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                // 生成新的文件名
                String fileNewName = imageName + "_" + simpleDateFormat.format(new Date()) + zhui;
                try {
                    // 将此图片存储到 images 文件夹中,
                    // 该方法是 springMVC 封装的方法,主要用于把内存中的图片写入到磁盘当中
                    multipartFile.transferTo(new File(aa + "\\" + fileNewName));
                    session.setAttribute("msg", "文件上传成功。");
                    return "redirect:/upload";
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                session.setAttribute("msg", "文件格式错误,上传失败!");
                return "redirect:/upload";
            }
        }
        session.setAttribute("msg", "文件为空,请重新选择。。");
        return "redirect:/upload";
    }
}

4、结果

选择文件后
在这里插入图片描述
点击提交后
在这里插入图片描述


到这里,实现的过程已经给出了,希望有帮助你们。

  • 3
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值