使用SpringMVC框架做个小练习,需求:

  1、单个图片上传并显示到页面中;

  2、多个图片上传并显示到页面中;

  3、上传文件后下载文件;

1、pom.xml中添加依赖

    <!-- 文件上传 -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>

    <!--jstl-->
    <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
    </dependency>
  </dependencies>

2、编写JSP页面

  • input 的 type 设置为 file  
  • form 表单的 method 设置为 post
  • form 表单的 enctype 设置为 multipart/form-data
      
  • 单文件上传页面upload.jsp
<!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="img"/>
    <input type="submit" value="上传"/><br/><br/>

    <c:if test="${filePath!=null && filePath!=''}">
        上传成功
        <a href="/download?filePath=${filePath}">下载</a>
    </c:if>
</form>
</body>
</html>
  • 多文件上传页面uploadMore.jsp
<!DOCTYPE html>
<%@ page contentType="text/html; charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/uploadMore" method="post" enctype="multipart/form-data">
    file1:<input type="file" name="imgs"/>
    file2:<input type="file" name="imgs"/>
    file3:<input type="file" name="imgs"/>
    <input type="submit" value="上传"/><br/>
    <c:if test="${filePath!=null && filePath!=''}">
        <h1>上传的图片</h1>
        <c:forEach items="${filePaths}" var="img">
            <img src="${img}" style="width: 300px;">
        </c:forEach>
    </c:if>
</form>
</body>
</html>

3、编写controller

package com.sunjian.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author sunjian
 * @date 2020/3/20 8:07
 */
@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(@RequestParam("img")MultipartFile img, HttpServletRequest request){

        if(img.getSize() > 0){
            // 获取target目录下的文件保存路径
            String path = (String) request.getSession().getServletContext().getRealPath("files");

            String fileName = img.getOriginalFilename();// 获取原始文件名
            File file = new File(path, fileName); // 创建空文件

            try {
                img.transferTo(file); // 将img中的内容转移到file这个空文件中
            } catch (IOException e) {
                e.printStackTrace();
            }
            request.setAttribute("filePath", "/files/"+fileName);
        }
        return "upload";
    }

    @RequestMapping("/uploadMore")
    public String uploadMore(@RequestParam("imgs") MultipartFile[] imgs, HttpServletRequest request){
        List<String> filePaths = new ArrayList<>();
        for(MultipartFile img:imgs){
            if(img.getSize() > 0){
                String path = request.getSession().getServletContext().getRealPath("files");
                String fileName = img.getOriginalFilename();

                File file = new File(path, fileName);// 创建文件
                try {
                    img.transferTo(file);
                    filePaths.add("/files/" + fileName); // 将文件路径添加到list中
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        request.setAttribute("filePaths", filePaths);
        return "uploadMore";
    }

    @RequestMapping("/download")
    public void download(String filePath, HttpServletRequest request, HttpServletResponse response){

        // 文件名处理
        filePath = filePath.split("/")[2];

        // 设置响应流文件进行下载
        response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
        try {
            ServletOutputStream servletOutputStream = response.getOutputStream();
            File file = new File(request.getSession().getServletContext().getRealPath("files"), filePath);

            byte[] bytes = FileUtils.readFileToByteArray(file);
            servletOutputStream.write(bytes);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

4、在springmvc.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-3.2.xsd">

    <!-- 配置自动扫描 -->
    <context:component-scan base-package="com.sunjian"></context:component-scan>

    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 消息转换器 -->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"></bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 自定义数据类型转换器 -->
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <list>
                <bean class="com.sunjian.converter.DataConverter">
                    <constructor-arg type="java.lang.String" value="yyyy-MM-dd"></constructor-arg>
                </bean>
                <bean class="com.sunjian.converter.goodsConverter"></bean>
            </list>
        </property>
    </bean>

    <!--文件上传-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 处理文件名中文乱码 -->
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 多文件上传总⼤小的上限 100M -->
        <property name="maxUploadSize" value="104857600"></property>
        <!-- 单文件大小的上限 10M -->
        <property name="maxUploadSizePerFile" value="10485760"></property>
    </bean>

    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
</beans>

5、启动项目,访问页面上传图片

  http://localhost:7777/upload.jsp

  

  http://localhost:7777/uploadMore.jsp

  

  下载

  

OK.

SpringMVC框架——文件的上传与下载的更多相关文章

  1. 使用springmvc进行文件的上传和下载

    文件的上传 SpringMVC支持文件上传组件,commons-fileupload,commons-fileupload依赖commons-io组件 配置步骤说明 第一步:导入包 commons-f ...

  2. SpringMVC 实现文件的上传与下载

    一  配置SpringMVC ,并导入与文件上传下载有关的jar包(在此不再赘述) 二 新建 相应 jsp 和controller FileUpAndDown.jsp <%@ page lang ...

  3. SpringMVC下文件的上传与下载以及文件列表的显示

    1.配置好SpringMVC环境-----SpringMVC的HelloWorld快速入门! 导入jar包:commons-fileupload-1.3.1.jar和commons-io-2.4.ja ...

  4. springMVC实现文件的上传和下载

    文件的下载功能 @RequestMapping("/testDown")public ResponseEntity<byte[]> testResponseEntity ...

  5. 基于struts2框架文件的上传与下载

    在开发一些社交网站时,需要有允许用户上传自己本地文件的功能,则需要文件的上传下载代码. 首先考虑的是文件的储存位置,这里不考虑存在数据库,因为通过数据库查询获取十分消耗资源与时间,故需将数据存储在服务 ...

  6. Spring MVC 实现文件的上传和下载

    前些天一位江苏经贸的学弟跟我留言问了我这样一个问题:“用什么技术来实现一般网页上文件的上传和下载?是框架还是Java中的IO流”.我回复他说:“使用Spring MVC框架可以做到这一点,因为Spri ...

  7. 在SpringMVC框架下实现文件的 上传和 下载

    在eclipse中的javaEE环境下:导入必要的架包 web.xml的配置文件: <?xml version="1.0" encoding="UTF-8" ...

  8. 文件的上传和下载--SpringMVC

    文件的上传和下载是项目开发中最常用的功能,例如图片的上传和下载.邮件附件的上传和下载等. 接下来,将对Spring MVC环境中文件的上传和下载进行详细的讲解. 一.文件上传 多数文件上传都是通过表单 ...

  9. SpringMVC+Ajax实现文件批量上传和下载功能实例代码

    需求: 文件批量上传,支持断点续传. 文件批量下载,支持断点续传. 使用JS能够实现批量下载,能够提供接口从指定url中下载文件并保存在本地指定路径中. 服务器不需要打包. 支持大文件断点下载.比如下 ...

随机推荐

  1. 算法拾遗[4]——STL用法

    主要bb一下优先队列和字符串吧. 哦还有 bitset. 优先队列 定义很容易: priority_queue<int> pq; 内部是一个堆. 基本操作 pq.top() 取堆顶元素; ...

  2. 内核ioctl函数的cmd宏参数

    在驱动程序里, ioctl() 函数上传送的变量 cmd 是应用程序用于区别设备驱动程序请求处理内容的值.cmd除了可区别数字外,还包含有助于处理的几种相应信息. cmd的大小为 32位,共分 4 个 ...

  3. 安卓权威编程指南 -笔记(19章 使用SoundPool播放音频)

    针对BeatBox应用,可以使用SoundPool这个特别定制的实用工具. SoundPool能加载一批声音资源到内存中,并支持同时播放多个音频文件.因此所以,就算用户兴奋起来,狂按按钮播放全部音频, ...

  4. 初识SpringIOC

    初识SpringIOC 简介 IOC(Inversion of Control)控制反转.指的是获取对象方式由原来主动获取,到被动接收的转变.在Spring中,IOC就是工厂模式解耦,是Srping框 ...

  5. HTML标签学习总结(3)

    */ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.cpp * 作者:常轩 * 微信公众号:Worldhe ...

  6. CSV文件注入漏洞简析

    “对于网络安全来说,一切的外部输入均是不可信的”.但是CSV文件注入漏洞确时常被疏忽,究其原因,可能是因为我们脑海里的第一印象是把CSV文件当作了普通的文本文件,未能引起警惕. 一.漏洞定义 攻击者通 ...

  7. 一位资深程序员大牛推荐的Java技术学习路线图

    Web应用,最常见的研发语言是Java和PHP. 后端服务,最常见的研发语言是Java和C/C++. 大数据,最常见的研发语言是Java和Python. 可以说,Java是现阶段中国互联网公司中,覆盖 ...

  8. java反序列化-ysoserial-调试分析总结篇(5)

    前言: 这篇文章继续分析commonscollections5,由如下调用链可以看到此时最外层的类不是annotationinvoke,也不是priorityqueue了,变成了badattribut ...

  9. 前端基础知识之HTML

    [1: What does a doctype do?] 1: doctype是html文件的第一行代码,意味着它的前面有注释都不行.所以要要写在<html>标签前面,而且它不属于html ...

  10. Python - loguru日志库,高效输出控制台日志和日志记录

    一.安装loguru loguru的PyPI地址为:https://pypi.org/project/loguru/ GitHub仓库地址为:https://github.com/Delgan/log ...