文件上传下载

文件上传下载

创建模块

文件上传下载_第1张图片

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>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    <init-param>
      <param-name>forceResponseEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  
  <filter>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>HiddenHttpMethodFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
  
  <servlet>
    <servlet-name>DispatcherServletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springMVC.xmlparam-value>
    init-param>
    
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>
web-app>

SpringMVC.xml


<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>
    
    <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.0modelVersion>
    <parent>
        <groupId>com.louisgroupId>
        <artifactId>springMVCartifactId>
        <version>1.0-SNAPSHOTversion>
    parent>
    <artifactId>springMVC-07artifactId>
    <packaging>warpackaging>
    <name>springMVC-07 Maven Webappname>
    <url>http://maven.apache.orgurl>
    <dependencies>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.1version>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.3.1version>
        dependency>
        <dependency>
            <groupId>org.thymeleafgroupId>
            <artifactId>thymeleaf-spring5artifactId>
            <version>3.0.12.RELEASEversion>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.15.2version>
        dependency>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.3version>
        dependency>
    dependencies>
    <build>
        <finalName>springMVC-07finalName>
    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.jpga>
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;
    }
}

⑤测试

文件上传下载_第2张图片

文件上传

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

实现步骤

①补充依赖

<dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.3version>
dependency>

②配置SpringMVC.xml

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


<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>Titletitle>
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文件夹中查看结果。

在这里插入图片描述
在这里插入图片描述
文件上传下载_第3张图片

完整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";
    }
}

你可能感兴趣的:(springMVC,java,mvc)