栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC学习(8)—— 文件上传和下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC学习(8)—— 文件上传和下载

一. 文件下载

使用ResponseEntity实现下载文件的功能,可以下载图片、文档、音频等各种类型

package com.mvc.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;
import java.io.InputStream;

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileDown")
    public ResponseEntity testFileDown(HttpSession session) throws IOException {
        //获取要下载的文件
        String downloadFile = "/static/img/school.jpg";

        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取文件在服务器中的真实路径
        String realPath = servletContext.getRealPath(downloadFile);

        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组,获取当前文件中所有的字节数
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);


        //创建HttpHeaders对象用于设置响应头信息
        MultiValueMap headers = new HttpHeaders();
        //设置响应头信息,Content-Disposition响应头表示收到的数据怎么处理(固定),attachment表示下载使用(固定),filename指定下载的文件名(下载时会在客户端显示该名字)
        headers.add("Content-Disposition", "attachment;filename=school.jpg");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;

        //创建ResponseEntity对象,bytes表示响应体(即图片内容),headers表示响应头,statusCode表示响应状态码
        ResponseEntity responseEntity = new ResponseEntity<>(bytes, headers, statusCode);

        //关闭输入流
        is.close();
        return responseEntity;
    }
}



    
    Title


    index.html页面

    下载图片

二. 文件上传

条件: 

①要有一个form标签,method = "post",enctype必须为"multipart/form-data"

②在form标签中使用input type="file"添加上传文件




    
    Title


    index.html页面

    
文件:

 ③添加依赖



    commons-fileupload
    commons-fileupload
    1.3.1

④在SpringMVC的核心配置文件配置文件上传解析器


实现文件上传:

package com.mvc.controller;

import org.springframework.stereotype.Controller;
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.IOException;
import java.util.UUID;

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileUp")
    public String testFileUp(MultipartFile document, HttpSession session) throws IOException {
        //获取上传的文件的文件名
        String fileName = document.getOriginalFilename();

        //处理文件重名问题(当上传的文件同名,新上传的文件会将原文件覆盖),因此将UUID作为文件名,来解决该问题
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //获取上传文件的后缀名
        fileName = UUID.randomUUID().toString() + suffixName;  //将UUID和后缀名拼接后的结果作为文件名

        //获取服务器中document目录的路径(将上传的文件放在服务器的document目录下)
        ServletContext servletContext = session.getServletContext();
        String documentPath = servletContext.getRealPath("document");

        //第一次上传时,上述服务器中不存在document目录,需要创建
        File file = new File(documentPath);
        //判断documentPath所对应的路径是否存在
        if(!file.exists()){
            file.mkdir();  //如果不存在,则创建目录
        }

        String finalPath = documentPath + File.separator + fileName;  //File.separator表示路径的分隔符

        //上传
        document.transferTo(new File(finalPath));

        return "index";
    }
}

 上述方法会将上传的目录存放在服务器target目录下的document目录中(如果没有document目录,则创建该目录)

下面的方法是自定义一个存储目录,将上传的文件存放在该目录下。

package com.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
public class FileUpAndDownController {
    @RequestMapping("/")
    public String index() {
        return "index";
    }

    @RequestMapping("/fileUp")
    public String testFileUp(MultipartFile document, HttpSession session) throws IOException {
        //获取上传的文件的文件名
        String fileName = document.getOriginalFilename();

        //处理文件重名问题(当上传的文件同名,新上传的文件会将原文件覆盖),因此将UUID作为文件名,来解决该问题
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  //获取上传文件的后缀名
        fileName = UUID.randomUUID().toString() + suffixName;  //将UUID和后缀名拼接后的结果作为文件名

        //设置上传的文件存放的目录
        String finalPath = "d:\" + fileName;

        //上传
        document.transferTo(new File(finalPath));

        return "index";
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837537.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号