SpringBoot整合文件上传

欢迎浏览我的博客 获取更多精彩文章

https://boyn.top

SpringBoot整合文件上传

在SpringBoot中,经常会遇到需要上传文件的场景.所以这次就来演示一下如何在SpringBoot中结合SpringMVC实现文件上传

单个文件上传

在网页中,分为表单上传和异步上传.所谓异步上传一般来说就是通过构建FormData对象用Ajax来上传.

这两种上传方式其后端接收都是一样的.先给出后端的代码

	@PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request) throws FileNotFoundException {
        String format = dateFormat.format(new Date());
        String realPath = ResourceUtils.getFile("classpath:static") + "/img" + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String oldName = file.getOriginalFilename();
        assert oldName != null;
        String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
        try {
            file.transferTo(new File(folder, newName));
            return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newName;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error";
    }

这个函数中,关键是要用MultipartFile作为参数来接收文件对象

一般来说,文件都会存在文件服务器中,但是这里为了方便,先将其存在项目的包中.

我们首先获取日期,打算根据年月日来划分文件夹.然后为了上传到项目的包中,我们要用ResourceUtils.getFile(“classpath:static”)的方法来获取静态资源的文件夹位置,并构建文件存放的路径(不存在时创建).之后,要构造新的文件名,用UUID.randomUUID().toString()来实现,然后用transferTo方法将其存放起来.

然后我们给出前端的代码

  • 表单上传

    
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit" value="提交">
    form>
    body>
    html>
    
  • Ajax上传

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <body>
    <div id="result"></div>
    <input type="file" id="file" multiple>
    <input type="button" value="上传" onclick="uploadFile()">
    <script>
        function uploadFile() {
            var formData = new FormData();
            var file = $("#file")[0].files[0];
    		formData.append("file",file);
            $.ajax({
                type:"post",
                url:"/uploads",
                processData:false,
                contentType:false,
                data:formData,
                success:function (msg) {
                    $("#result").html(msg);
                }
            })
        }
    </script>
    </body>
    </html>
    

只要选择好图片,就可以进行上传了

当上传成功后,页面会返回一个url,指示文件的访问位置

图片在项目中的结构如图所示

SpringBoot整合文件上传_第1张图片

多个文件上传

多个文件上传其实就是将后端函数中的file改成数组形式,并根据其长度一个个存文件.

@PostMapping("/uploads")
    public String uploads(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws FileNotFoundException {
        String format = dateFormat.format(new Date());
        String realPath = ResourceUtils.getFile("classpath:static") + "/img" + format;
        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        for (MultipartFile file : files) {
            String oldName = file.getOriginalFilename();
            assert oldName != null;
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
            try {
                file.transferTo(new File(folder, newName));
                String url =  request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/img" + format + newName;
//                System.out.println(url);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

而前端上面,表单上传只要在input标签中加入multiple就可以了.还可以用accept来标记接受上传文件的格式

<input type="file" name="file" multiple accept="image/jpeg,image/png">

如果用Ajax上传,不仅要在input标签中加入multiple,还要遍历file对象,将其逐个添加到formData表单中.


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js">script>
<body>
<div id="result">div>
<input type="file" id="file" multiple>
<input type="button" value="上传" onclick="uploadFile()">
<script>
    function uploadFile() {
        var formData = new FormData();
        for(var i=0; i<$('#file')[0].files.length;i++){
            formData.append('file', $('#file')[0].files[i]);
        }

        $.ajax({
            type:"post",
            url:"/uploads",
            processData:false,
            contentType:false,
            data:formData,
            success:function (msg) {
                $("#result").html(msg);
            }
        })
    }
script>
body>
html>

你可能感兴趣的:(Java,Spring,Springboot,SpringBoot2爬塔笔记)