springmvc中设置文件的上传与下载,首先需要导入依赖,之后需要在springmvc.xml中配置问价上传解析器。在上传文件的时候设置 一个form表单里面设置一个输入框,类型为file,为了防止上传同名文件被覆盖,上传文件名称时,需要使用UUID进行文件名的拼接

发布时间 2023-09-16 10:30:04作者: 努力是一种常态

2023-09-16

导入依赖

 <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

设置文件上传解析器

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
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

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

    <!--设置前端控制器-->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"></property>
        <property name="characterEncoding" value="UTF-8"></property>
        <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>
                        <!--视图后缀-->
                        <property name="suffix" value=".html"></property>
                        <property name="templateMode" value="HTML5"></property>
                        <property name="characterEncoding" value="UTF-8"></property>
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

    <!--设置默认的servlet处理静态资源-->
    <mvc:default-servlet-handler/>

    <!--开启视图注解驱动器-->
    <mvc:annotation-driven />

    <mvc:view-controller path="/" view-name="index"></mvc:view-controller>

    <!--配置文件上传的解析器-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>

index.html文件

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
<div id="app">
    <h1>index.html</h1>
    <input type="button" @click="testAjax()" value="测试ajax">
    <input type="button" @click="testRequestBody()" value="测试requestBody">
    <input type="button" @click="testRequestBodyJson()" value="测试requestBodyJson"><br>
    <a th:href="@{/test/responseBody}">测试responseBody</a>
    <a th:href="@{/test/down}">测试文件下载</a>
    <form th:action="@{/test/up}" method="post" enctype="multipart/form-data">
        头像:<input type="file" name="photo"><br>
        <input type="submit" value="上传">
    </form>
</div>
<script type="text/javascript" th:src="@{/js/vue.js}"></script>
<script type="text/javascript" th:src="@{/js/axios.min.js}"></script>
<script type="text/javascript">
    new Vue({
        el:"#app",
        methods:{
            testAjax(){
                axios.post(
                    "/spring_mvc_ajax_war_exploded/test/ajax?id=1002",
                    {username:"root",password:"123456"}
                ).then(response=>{
                    console.log(response.data)
                })
            },
            testRequestBody(){
                axios.post(
                    "/spring_mvc_ajax_war_exploded/test/ajax/requestbody",
                    {id:1,name:"jack",age:18,gender:""}
                ).then(response=>{
                    console.log(response.data)
                })
            },
            testRequestBodyJson(){
                axios.post(
                    "/spring_mvc_ajax_war_exploded/test/responseBodyJson"
                ).then(response=>{
                    console.log(response.data)
                })
            }

        }
    })
</script>
</body>
</html>

FileUpAndDownController

package com.hh.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.*;
import java.util.UUID;

/**
 * @author hh
 * @version 1.0
 * @DATE 2023-09-16 9:25:49
 */
@Controller
public class FileUpAndDownController {

    @RequestMapping("/test/up")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        //获取上传文件的文件名
        String fileName = photo.getOriginalFilename();
        //获取上传文件的后缀名
        String hzName = fileName.substring(fileName.lastIndexOf("."));
        //获取UUID
        String uuid = UUID.randomUUID().toString();
        //拼接一个新的文件名(为了防止上传同名的文件,导致文件内容被覆盖)
        fileName = uuid +hzName;

        //获取servletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取photo的真实路径
        String photoPath = servletContext.getRealPath("photo");
        //创建photoPath所对应的File对象
        File file = new File(photoPath);
        //判断file所对应的目录是否存在
        if(!file.exists()){
            file.mkdir();
        }
        String finalPath = photoPath+File.separator+fileName;
        //上传文件
        photo.transferTo(new File(finalPath));

        return "success";
    }

    @RequestMapping("/test/down")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/img/1.jpg");
        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String,String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition","attachment;filename=1.jpg");
        //设置响应码
        HttpStatus statusCode = HttpStatus.OK;
        //出啊关键ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes,headers,statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }
}