文件上传下载(图文案例)

1、案例:文件上传下载

文件上传,常用的大概有两种:
1、设置表单属性enctype=“multipart/form-data”,使得表单中每一个文件都是一个单独的组件;
2、通过type="file"选择文件,将文件编码得到base64数据,表单无需添加enctype="multipart/form-data"属性,直接作为普通表单上传即可。
文件下载,主要操作,是通过HttpServletResponse设置两个响应头信息,最后再通过HttpServletResponse中的输出流向页面输出数据。

这里会使用到本人自己封装的其他类,有兴趣的可以了解一下
FileUtils.java类:https://blog.csdn.net/weixin_43978412/article/details/108099849
GeneralUtils.java类:https://blog.csdn.net/weixin_43978412/article/details/108100100

1.1、导入依赖

由于只模拟文件上传功能,因此本次不涉及DB操作。

    <!-- 配置编译环境 -->
    <build>
        <plugins>
            <!-- 处理项目JDK编译版本的问题 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <!-- 设置maven内置服务器为tomcat7 -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>

    <!-- 属性 -->
    <properties>
        <!-- 指定spring的版本 -->
        <spring.version>5.1.9.RELEASE</spring.version>
        <!-- 指定mybatis的版本 -->
        <mybatis.version>3.5.2</mybatis.version>
        <!-- 指定mybatis和spring整合依赖的版本 -->
        <mybatis.spring.version>2.0.2</mybatis.spring.version>
        <!-- 指定mysql数据库的版本 -->
        <mysql.version>8.0.20</mysql.version>
        <!-- 指定redis数据库的版本 -->
        <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
    </properties>

    <!-- 锁定版本 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aspects</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-expression</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-orm</artifactId>
                <version>${spring.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <!-- 依赖 -->
    <dependencies>
        <!-- servlet-api依赖 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- jsp-api依赖 -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>

        <!-- springmvc的依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- jstl标签库 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- spring在web.xml进行配置的依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring的IOC依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <!-- spring的AOP依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- spring对AspectJ框架的支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
        <!-- 支持注解开发的aop -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- spring的声明式事务 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- log4j日志依赖 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.12.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.8.0-beta4</version>
        </dependency>

        <!-- 处理base64格式数据的依赖 -->
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.13</version>
        </dependency>

        <!-- 处理json数据的依赖 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>

        <!-- 封装map数据到javabean中 -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.4</version>
        </dependency>

        <!-- IO流 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- 文件上传 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.4</version>
        </dependency>

        <!-- dom4j解析文档依赖 -->
        <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>

    </dependencies>

1.2、配置项目环境

1.2.1、创建applicationContext-mvc.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">

    <context:component-scan base-package="com.wnkj.controller" />

    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

1.2.2、配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/applicationContext-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

1.3、创建控制器类

package com.wnkj.controller;

import com.wnkj.utils.FileUtils;
import com.wnkj.utils.GeneralUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

@Controller
@RequestMapping(value = "/file")
public class FileController {

    /**
     * 上传文件
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value = "/uploadFile")
    public ModelAndView uploadFile(HttpServletRequest request) throws Exception {

        Map<String, Object> map = FileUtils.uploadFile(request, "avatar");

        String avatar = (String) map.get("avatar");
        System.out.println("avatar = " + avatar);

        ModelAndView mv = new ModelAndView();
        mv.addObject("fileName", avatar);
        mv.setViewName("show");
        return mv;
    }

    /**
     * 下载文件
     * @param response
     * @throws Exception
     */
    @GetMapping(value = "/downloadFile")
    public void downloadFile(String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("fileName = " + fileName);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + GeneralUtils.get32UUID() + ".jpg\"");

        String path = FileUtils.getFileAccessPath(request, fileName);
        System.out.println("path = " + path);
        InputStream input = new FileInputStream(path);

        OutputStream output = response.getOutputStream();

        byte[] buf = new byte[1024];
        int len = 0;
        while((len = input.read(buf)) != -1) {
            output.write(buf, 0, len);
        }

        output.flush();
    }

}

1.4、前端jsp页面

1.4.1、show.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html>
<head>
    <base href="<%=basePath%>">
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="<%=basePath%>file/uploadFile" method="POST">
        <p id="content">暂无图片</p>
        <img id="imgNode" src="" width="200px" height="200px" style="display:none;"/><br/>
        <p>文件名称:<span id="fileName"></span></p>
        <p>文件大小:<span id="fileSize"></span></p>
        <p>最后修改时间:<span id="lastModifyDate"></span></p>
        <input type="hidden" name="avatar" id="avatar" /><br/>
        <input type="file" id="avatarFile" style="display: none;" /><br/>
        <a id="chooseImage" style="border:1px solid darkgrey; font-size: 10px; background-color:skyblue; padding:5px;">选择图片</a><br/>
        <br/>
        <input type="submit" value="上传" />
    </form>
    <br/>
<a href="<%=basePath%>file/downloadFile?fileName=${requestScope.fileName}">下载图片</a>
</body>
<script type="text/javascript">

    window.onload = function() {

        var oAChooseImage = document.getElementById("chooseImage");
        var oInputAvatarFile = document.getElementById("avatarFile");
        oAChooseImage.onclick = function() {
            oInputAvatarFile.click();
        };

        oInputAvatarFile.onchange = function() {
            var avatarFile = this.files[0];

            var oPContent = document.getElementById("content");
            var oImgImgNode = document.getElementById("imgNode");
            var oSpanFileName = document.getElementById("fileName");
            var oSpanFileSize = document.getElementById("fileSize");
            var oSpanLastModifyDate = document.getElementById("lastModifyDate");
            var oInputAvatar = document.getElementById("avatar");

            if (avatarFile === undefined) {
                oPContent.style.display = 'block';
                oImgImgNode.setAttribute('src', '');
                oImgImgNode.style.display = 'none';
                oSpanFileName.innerHTML = '';
                oSpanFileSize.innerHTML = '';
                oSpanLastModifyDate.innerHTML = '';
                oInputAvatar.setAttribute('value', '');
                return;
            }
            var avatarFileName = avatarFile.name;
            var lastModifyDate = new Date(avatarFile.lastModified).toLocaleDateString();
            getBase64ByFile(avatarFile, function(base64Data, fileSize) {
                oPContent.style.display = 'none';
                oImgImgNode.setAttribute('src', base64Data);
                oImgImgNode.style.display = 'block';
                oSpanFileName.innerHTML = avatarFileName;
                oSpanFileSize.innerHTML = fileSize;
                oSpanLastModifyDate.innerHTML = lastModifyDate;
                oInputAvatar.setAttribute('value', base64Data);
            })
        };

        function getBase64ByFile(file, callback) {
            var fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = function() {
                var result = fileReader.result;
                callback(result, result.length);
            }
        }

    }

</script>
</html>

1.4.2、index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<jsp:forward page="show.jsp" />

1.5、测试效果

项目启动,显示如下页面:

文件上传下载(图文案例)_第1张图片

点击按钮“选择图片”,会有一个预览效果
注:本次使用的是base64上传文件,base64才支持在线预览,因为浏览器能直接解析base64数据,如果是enctype="multipart/form-data"则不支持预览

文件上传下载(图文案例)_第2张图片

点击上传,后端会处理上传并返回图片链接,查看 超链接“下载图片”中的地址信息,可以看到已经把后端返回的图片链接作为参数拼接到 地址中:

文件上传下载(图文案例)_第3张图片

点击下载图片,就会弹出保存框:

文件上传下载(图文案例)_第4张图片

查看文件夹,如下:

文件上传下载(图文案例)_第5张图片

至此,文件上传下载完成。

你可能感兴趣的:(需求案例,个人笔记,java,spring,经验分享,程序人生)