springboot开发指南(五)——文件上传(页面跳转方式和ajax方式),多文件上传,文件下载

项目简介:本文实现了单个文件上传两种方式(页面跳转方式和ajax方式),多个文件上传和文件下载方式

目录

目录

一. 项目效果

 二.  使用的技术和项目依赖

三. 单个文件上传(页面跳转方式)

四. 文件上传ajax方式

五. 多文件上传(页面跳转方式)

六. 文件下载

七 配置文件上传大小

八  js清空文件

九  文件上传文件编写了一个FileUtils, 可直接调用


 

一. 项目效果


 二.  使用的技术和项目依赖

1. 技术:主要使用MultipartFile这个类接收前台传过来的文件,方法说明如下:

函数函数说明返回值
getBytes()将文件内容转化成一个byte[] 返回byte[]
getContentType()返回文件的内容类型String
getInputStream()返回InputStream读取文件的内容Inputstream
getName()返回参数的名称String
getSize()返回文件大小 以字节为单位Long
isEmpty()判断是否为空,或者上传的文件是否有内容Boolean
transferTo(File dest)用来把 MultipartFile 转换换成 FileVoid

2.项目依赖:thymeleaf 

<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.0.1</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.28</version>
		</dependency>
</dependencies>

三. 单个文件上传(页面跳转方式)

前端file.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form id="formfile" action="fileUpload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="fileName"/></p>
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>

后端Controller:

@Controller
public class FileUploadController {
    /*
     * 获取file.html页面
     */
    @RequestMapping("file")
    public String file(){
        return "/file";
    }

    /**
     * 实现文件上传
     * */
    @RequestMapping("fileUpload")
    @ResponseBody
    public String fileUpload(@RequestParam("fileName") MultipartFile file){
        System.out.println("=================fileUpload==============");
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "/Users/whale/Documents" ;
         //此地址是mac地址,如果是windows则改为E:/users
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }
    }

四. 文件上传ajax方式

前端fileload.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <script src="asserts/js/jquery-3.4.0.min.js"></script>
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form id="formfile" action="multifileUpload" method="post" enctype="multipart/form-data">
    <p>选择文件: <input type="file" name="fileName"/></p>
    <p><input type="button" value="提交" onclick="fileSubmit()" /></p>
</form>
</body>
<script>
function fileSubmit() {
    alert("fileSubmit");
    //获取表单,必须加[0]才能取到数据
   var formData =new FormData(document.getElementById("formfile"));
             $.ajax({
                 url: "fileAjaxLoad",
                 type: "POST",
                 data: formData,
                 cache:false,
                 contentType: false,
                 processData: false,
                 success: function (dat) {
                 alert("success");

                 },
                 error: function (dat) {
                   alert("fail");
                 }
             });
             }

</script>
</html>

后端controller

@Controller
public class FileUploadController {

    @RequestMapping("fileload")
    public String fileload(){
        return "/fileload";
    }

    /**
     * 实现文件ajax上传
     * */
    @RequestMapping("fileAjaxLoad")
    @ResponseBody
    public String fileAjaxLoad(HttpServletRequest request){
        System.out.println("=================fileAjaxLoad==============");
        MultipartFile file = ((MultipartHttpServletRequest)request).getFile("fileName");
        if(file.isEmpty()){
            return "false";
        }
        String fileName = file.getOriginalFilename();
        int size = (int) file.getSize();
        System.out.println(fileName + "-->" + size);

        String path = "/Users/whale/Documents" ;
        File dest = new File(path + "/" + fileName);
        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            return "true";
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }
    }

五. 多文件上传(页面跳转方式)

前端multifile.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h1 th:inlines="text">文件上传</h1>
<form action="multifileUpload" method="post" enctype="multipart/form-data" >
    <p>选择文件1: <input type="file" name="fileName"  multiple="multiple"/></p>
   <!-- <p>选择文件2: <input type="file" name="fileName"/></p>
    <p>选择文件3: <input type="file" name="fileName" multiple="multiple"/></p>-->
    <p><input type="submit" value="提交"/></p>
</form>
</body>
</html>

后端Controller

 /*
     * 获取multifile.html页面
     */
    @RequestMapping("multifile")
    public String multifile(){
        return "/multifile";
    }

    /**
     * 实现多文件上传
     * */
    @RequestMapping(value="multifileUpload",method= RequestMethod.POST)
    /**public @ResponseBody String multifileUpload(@RequestParam("fileName")List<MultipartFile> files) */
    public @ResponseBody String multifileUpload(HttpServletRequest request){

        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        System.out.println("=================multifileUpload==============");
        if(files.isEmpty()){
            return "false";
        }

        String path = "/Users/whale/Documents" ;

        for(MultipartFile file:files){
            String fileName = file.getOriginalFilename();
            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if(file.isEmpty()){
                System.out.println("file.isEmpty()");
                return "false";
            }else{
                File dest = new File(path + "/" + fileName);
                if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                }catch (Exception e) {
                    // TODO Auto-generated catch block
                    System.out.println(e.toString());
                    e.printStackTrace();
                    return "false";
                }
            }
        }
        return "true";
    }

六. 文件下载

前端fileload.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
    <meta charset="UTF-8" />
    <script src="asserts/js/jquery-3.4.0.min.js"></script>
    <title>Insert title here</title>
</head>
<body>
<form  action="download" method="post">
    <p>1.doc<input type="submit" value="下载文件"/></p>
</form>
</body>
</html>

后端Controller

@RequestMapping("/download")
    public String downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
        String filename="1.doc";
        String filePath = "/Users/whale/Documents" ;  //mac地址
       //String filePath ="D:/web/upload";   //windows地址
        File file = new File(filePath + "/" + filename);
        if(file.exists()){ //判断文件父目录是否存在
            //response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            //response.setCharacterEncoding("UTF-8");
             response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(filename,"UTF-8"));
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

注意:如果要用ajax 发送的话,则浏览器没有任何反应  因为ajax返回的格式是字符的格式 

方法1:可以写成window.location.href="download";

function fileDown()
{
     window.location.href="download";
}

带参数的可以写成

function communication_downLoad()
{
     var jobId = $('#JobId').val(); 
      window.open("/qcs/export/"+jobId);
}

后台接收格式

@RequestMapping(value = "/qcs/export/{jobId}")
public void ExportBankCkeckInfo(HttpServletResponse response, HttpServletRequest request, @PathVariable("jobId") Integer jobId)

方法2:ajax不支持流形式,改成了表单提交解决。

<form class="form-signin" th:action="@{/download}" method="post">
    <input id="fileId"  name="fileName" value="">
    <p>1.doc<input type="submit" value="下载" >
</form>

七 配置文件上传大小

    springboot默认的文件上传大小为1M,当上传比较大的问题件时会报错,是因为SpringBoot自带集成的Tomcat限制了文件上传大小,需要在application.yml配置文件中重新设置

SpringBoot 2.0配置文件大小:

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 100Mb
      max-request-size: 100Mb

也可以编写配置bean

@Configuration
public class UploadConfig {
    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize(DataSize.parse("100MB"));
        // 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("100MB"));
        return factory.createMultipartConfig();
    }
 
}

八  js清空文件

$("#inputFilePath").replaceWith('<input id="inputFilePath" name="filePath" type="file" class="file-loading">');

九  文件上传文件编写了一个FileUtils, 可直接调用


public class FileUtils {
    public String filePath;

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public FileUtils() {
        filePath = "D:/whale/Documents";
        Properties prop = System.getProperties();
        String osname = prop.getProperty("os.name");
        System.out.println("osname====" + osname);
        if (osname != null && osname.toLowerCase().indexOf("linux") > -1) {
            filePath = "/usr/local/java/whale/Documents"; //linux address
        } else if (osname.toLowerCase().indexOf("mac") > -1) {
            filePath = "/Users/whale/Documents";
        } else {

            filePath = "D:/whale/Documents";
        }

    }

    public String getFilePath() {
        return filePath;
    }

    //单文件上传,最大有限制。。。。
    public static String singleFileUpload(MultipartFile file, String filePath) {

        if (file.isEmpty()) {
            return "false";
        }
        String fileName = file.getOriginalFilename();

        System.out.println("old Name:" + fileName);
        String newName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
        System.out.println("new Name:" + newName);


        int size = (int) file.getSize();

        File dest = new File(filePath, newName);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        //System.out.println("父目录存在===" + dest.getParentFile().getAbsolutePath());
        try {
            file.transferTo(dest); //保存文件
            return newName;
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "false";
        }
    }



    //多文件上传
    public  String multifileUpload(List<MultipartFile> files, String filePath) {


        for (MultipartFile file : files) {
            String fileName = file.getOriginalFilename();

            System.out.println("old Name:" + fileName);
            String newName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
            System.out.println("new Name:" + newName);

            int size = (int) file.getSize();
            System.out.println(fileName + "-->" + size);

            if (file.isEmpty()) {
                System.out.println("file.isEmpty()");
                return "false";
            } else {
                File dest = new File(filePath + "/" + newName);
                if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    System.out.println(e.toString());
                    e.printStackTrace();
                    return "false";
                }
            }
        }
        return "true";
    }

    //文件下载,存在文件名是乱码现象

    public static String fileDown(HttpServletResponse response, String filename, String filePath) throws UnsupportedEncodingException {
        File file = new File(filePath, filename);
        System.out.println("文件存在===" + file.getAbsolutePath());
        if (file.exists()) { //判断文件父目录是否存在

            // response.setContentType("application/force-download");
            //response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(filename, "UTF-8"));


            response.setContentType("multipart/form-data");
            //response.setContentType("multipart/form-data;charset=UTF-8");也可以明确的设置一下UTF-8,测试中不设置也可以。
            response.setHeader("Content-Disposition", "attachment; fileName="+  filename +";filename*=utf-8''"+ URLEncoder.encode(filename,"UTF-8"));



            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;

            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
                System.out.println("下载成功");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("下载失败");
            }
            System.out.println("----------file download---" + filename);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return "true";
        } else
            return "false";

    }
}

使用方式:

//文件上传
@ResponseBody
@RequestMapping("qcs/addFile")
public String adfile(@RequestParam MultipartFile filePath) {

    FileUtils fileUtils=new FileUtils();
    String newFilePath=fileUtils.singleFileUpload(filePath,fileUtils.getFilePath());
    System.out.println(filePath.getOriginalFilename());
    return "success";
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值