文件上传下载

文件上传下载

创建模块

在这里插入图片描述

web.xml

<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">
  <!--配置编码过滤器-->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
      <param-name>forceResponseEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置请求方式put和delete的hiddenHttpMethodFilter-->
  <filter>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!--配置springMVC的前端控制器DispatcherServlet-->
  <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:springMVC.xml</param-value>
    </init-param>
    <!--将前端控制器的时间提前到服务器启动时-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

SpringMVC.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--开启扫描组件-->
    <context:component-scan base-package="com.louis"></context:component-scan>
    <!--配值Thymeleaf视图解析器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <property name="prefix" value="/WEB-INF/templates/"/>
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/>
                        <property name="characterEncoding" value="UTF-8"/>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>
</beans>

依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.louis</groupId>
        <artifactId>springMVC</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <artifactId>springMVC-07</artifactId>
    <packaging>war</packaging>
    <name>springMVC-07 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>springMVC-07</finalName>
    </build>
</project>

文件下载

将文件从服务器端下载到浏览器端,本质是文件复制,使用ResponseEntity可以实现文件下载的功能。

实现步骤

①目标内容

网上下载目标文件(图片)复制到static下的img文件夹中

在这里插入图片描述

②创建页面

在templates下创建首页的文件index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
    <title>测试文件上传和下载</title>
</head>
<body>
<a th:href="@{/testDown}">下载1.jpg</a>
</body>
</html>
③配置SpringMVC.xml

由于查看首页只涉及到页面跳转没有业务功能,所以只需要在SpringMVC.xml下进行配置即可。不需要单独的控制器。

<!--用来实现页面跳转-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<mvc:annotation-driven></mvc:annotation-driven>
④FileUpAndDownController

在controller下创建FileUpAndDownController控制器

package com.louis.controller;


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author XRY
 * @date 2023年07月04日15:10
 */
@Controller
public class FileUpAndDownController {
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/1.jpg");
        //创建输入流
        FileInputStream fis = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[fis.available()];
        //将流读到字节数组中
        fis.read(bytes);
        //创建HttpHeaders对象设置响应头信息,Map---响应头是键值对
        MultiValueMap<String, String> httpHeaders = new HttpHeaders();
        //设置下载方式以及下载文件的名字,只能修改文件名,其他都是固定写法,设置下载方式
        httpHeaders.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, statusCode);
        //关闭输入流
        fis.close();
        return responseEntity;
    }
}
⑤测试

在这里插入图片描述

文件上传

文件上传要求form表单的请求方式必须为post,并且添加属性enctype=“multipart/form-data”,SpringMVC中上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息。

实现步骤

①补充依赖
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
②配置SpringMVC.xml

在SpringMVC.xml配置文件上传解析器

<!--配置文件上传解析器,将上传的文件封装为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
③index.html
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="photo"><br/>
    <input type="submit" value="上传">
</form>
④success.html

创建上传成功之后跳转的页面success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" xmlns:th="http://www.thymeleaf.org">
    <title>Title</title>
</head>
<body>
上传成功
</body>
</html>
⑤FileUpAndDownController
@RequestMapping("/testUp")
//将上传的文件进行封装,但上传的文件不能直接转换为MultipartFile对象,需要配置文件上传解析器
//使用session获取服务器路径
public String testUp(MultipartFile photo, HttpSession session) throws IOException {
    //上传操作
    System.out.println(photo.getName());//photo
    System.out.println(photo.getOriginalFilename());//24f2a9d47e3673a094df34c5260a081f.jpeg

    String fileName = photo.getOriginalFilename();
    ServletContext servletContext = session.getServletContext();
    String photoPath = servletContext.getRealPath("photo");//将文件上传到服务器的photo目录下
    File file = new File(photoPath);
    //判断photoPath所对应路径是否存在
    if(!file.exists()){
        //不存在,则创建目录
        file.mkdir();
    }
    //File.separator用于设置分隔符,/或\
    String finalPath = photoPath + File.separator + fileName;
    photo.transferTo(new File(finalPath));
    return "success";
}
⑥测试

在target下打开当前项目的目录位置,在其中的photo文件夹中查看结果。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

完整controller

package com.louis.controller;


import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author XRY
 * @date 2023年07月04日15:10
 */
@Controller
public class FileUpAndDownController {
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/1.jpg");
        //创建输入流
        FileInputStream fis = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[fis.available()];
        //将流读到字节数组中
        fis.read(bytes);
        //创建HttpHeaders对象设置响应头信息,Map---响应头是键值对
        MultiValueMap<String, String> httpHeaders = new HttpHeaders();
        //设置下载方式以及下载文件的名字,只能修改文件名,其他都是固定写法,设置下载方式
        httpHeaders.add("Content-Disposition", "attachment;filename=1.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, httpHeaders, statusCode);
        //关闭输入流
        fis.close();
        return responseEntity;
    }

    @RequestMapping("/testUp")
    //将上传的文件进行封装,但上传的文件不能直接转换为MultipartFile对象,需要配置文件上传解析器
    //使用session获取服务器路径
    public String testUp(MultipartFile photo, HttpSession session) throws IOException {
        //上传操作
        System.out.println(photo.getName());//photo
        System.out.println(photo.getOriginalFilename());//picture.jpeg
        //获取上传文件的文件名
        String fileName = photo.getOriginalFilename();
        //解决文件重名问题
        //1、获取上传文件的后缀名,获取最后一个点
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //2、将UUID作为文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        //3、将UUID和后缀拼接后的结果作为最终文件名
        fileName = uuid + suffixName;
        //通过ServletContext获取服务器中photo目录的路径
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");//将文件上传到服务器的photo目录下
        File file = new File(photoPath);
        //判断photoPath所对应路径是否存在
        if(!file.exists()){
            //不存在,则创建目录
            file.mkdir();
        }
        //File.separator用于设置分隔符,/或\
        String finalPath = photoPath + File.separator + fileName;
        photo.transferTo(new File(finalPath));
        return "success";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值