SpringBoot+Vue实现文件上传+预览

Stella981
• 阅读 511

从松哥的微信公众号上面看到了SpringBoot+Vue实现文件上传+预览的视频教程,如下图所示:
SpringBoot+Vue实现文件上传+预览

跟着做,使用IDEA一遍看一边做,没想到由于自己马虎将日期SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");写成了SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");导致后续拼接文件名出错:
SpringBoot+Vue实现文件上传+预览
由于在本地地址生成pdf文件失败导致无法实现预览PDF文件的效果。
最后将日期格式修改后成功上传并且可以实现pdf文件预览。
SpringBoot+Vue实现文件上传+预览

SpringBoot+Vue实现文件上传+预览

创建SpringBoot项目

pom.xml文件

使用IDEA创建一个基于SpringBoot的项目,依赖选择Spring Web,我的pom.xml文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>org.javaboy</groupId>
    <artifactId>fileupload</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>fileupload</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

添加一个FileUploadController.java控制器类

package org.javaboy.fileupload;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class FileUploadController {
   
   
   

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");

    @PostMapping("/upload")
    public Map<String, Object> fileUpload(MultipartFile file, HttpServletRequest req) {
   
   
   
        Map<String, Object> resultMap = new HashMap<>();

        // 得到上传时的文件名
        String originName = file.getOriginalFilename();
        if (!originName.endsWith(".pdf")) {
   
   
   
            resultMap.put("status", "error");
            resultMap.put("msg", "文件类型不对,必须为pdf");

            return resultMap;
        }

        String strFormat = simpleDateFormat.format(new Date());
        String realPath = req.getServletContext().getRealPath("/") + strFormat;
        String uploadDir = req.getSession().getServletContext().getRealPath("/") + "/upload/" + strFormat;

        File folder = new File(realPath);
        if (!folder.exists()) {
   
   
   
            folder.mkdirs();
        }

        // 保存文件对象,加上uuid是为了防止文件重名
        String strNewFileName = UUID.randomUUID().toString().replaceAll("-", "") + ".pdf";
        try {
   
   
   
            file.transferTo(new File(folder, strNewFileName));
            String strUrl = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + strFormat + strNewFileName;
            resultMap.put("status", "success");
            resultMap.put("url", strUrl);
        } catch (IOException e) {
   
   
   
            e.printStackTrace();

            resultMap.put("status", "error");
            resultMap.put("msg", e.getMessage());
        }

        return resultMap;
    }
}

index.html

为了简单直接在resources/static目录下创建index.html,并且引入vue.js和elment-ui,具体可以参考Element-UI安装
对应的页面内容如下图所示:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <el-upload
        action="/upload"
        :on-preview="handlePreview"
        multiple
        :limit="10"
        accept=".pdf">
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传pdf文件,且不超过100MB</div>
    </el-upload>
</div>
</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
    
    
    
        el: '#app',
        methods: {
    
    
    
            handlePreview(file) {
    
    
    
                console.log(file);
                window.open( file.response.url);
            }
        }
    })
</script>
</html>

这里使用了Element-UI的el-upload组件,如下所示:
SpringBoot+Vue实现文件上传+预览

需要注意的问题

SpringBoot上传文件的大小限制

SpringBoot对于上传的文件大小有限制,所以需要在application.properties文件中增加几个配置,如下:

#配置文件传输
spring.servlet.multipart.enabled =true
spring.servlet.multipart.file-size-threshold =0
#设置单个文件上传的数据大小
spring.servlet.multipart.max-file-size = 100MB
#设置总上传的数据大小
spring.servlet.multipart.max-request-size=100MB

我这里设置单文件上传的最大大小为100MB和总共文件的大小为100MB

最终源代码下载

相关代码我已经上传至我的Github和Gitee码云仓库上面了,需要的话可自行获取

从github上面克隆fileupload项目

git clone https://github.com/ccf19881030/fileupload.git

从码云上获取fileupload项目

git clone https://gitee.com/havealex/fileupload.git

参考资料

本文同步分享在 博客“雪域迷影”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

点赞
收藏
评论区
推荐文章
浅梦一笑 浅梦一笑
6个月前
初学 Python 需要安装哪些软件?超级实用,小白必看!
编程这个东西是真的奇妙。对于懂得的人来说,会觉得这个工具是多么的好用、有趣,而对于小白来说,就如同大山一样。其实这个都可以理解,大家都是这样过来的。那么接下来就说一下python相关的东西吧,并说一下我对编程的理解。本人也是小白一名,如有不对的地方,还请各位大神指出01名词解释:如果在编程方面接触的比较少,那么对于软件这一块,有几个名词一定要了解,比如开发环
blmius blmius
1年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
光头强的博客 光头强的博客
6个月前
Java面向对象试题
1、请创建一个Animal动物类,要求有方法eat()方法,方法输出一条语句“吃东西”。创建一个接口A,接口里有一个抽象方法fly()。创建一个Bird类继承Animal类并实现接口A里的方法输出一条有语句“鸟儿飞翔”,重写eat()方法输出一条语句“鸟儿吃虫”。在Test类中向上转型创建b对象,调用eat方法。然后向下转型调用eat()方
刚刚好 刚刚好
6个月前
css问题
1、在IOS中图片不显示(给图片加了圆角或者img没有父级)<div<imgsrc""/</divdiv{width:20px;height:20px;borderradius:20px;overflow:h
小森森 小森森
3天前
租房类微信小程序-基于微信云开发-小程序端集成了管理员后台-一键部署,快速发布
温馨提醒本项目使用MITLicense协议,仅适用于学习交流,并且不提供无偿的、不提供无偿的、不提供无偿的维护修改服务(但可提issue)。若直接将本项目用于商用,因本项目带来的所有后果由使用者自行承担。如需商用升级版,请联系我微信,微信二维码在本博客页面右上角在此奉劝某些人,请尊重作者的劳动成果,做人积点德吧!最近发现有人拿我的源码进行二次分
小森森 小森森
3天前
计划助手V1.0-微信小程序(QQ小程序)-源代码分享
疫情期间在家感觉好无聊啊,于是利用空闲时间做了一个用来记录和管理小目标时间的小程序,命名为《小沙漏》。QQ版本小程序同步上线,QQ小程序叫《时间小沙漏》,欢迎大家前来体验,后期也会添加其他的新功能哦【区别】:微信小程序的代码与QQ小程序的源码是不一样的。微信小程序的源码基于微信小程序云开发,需要在有网络的情况下使用,具有同步功能,所有记录在删除小
小森森 小森森
6个月前
校园表白墙微信小程序V1.0 SayLove -基于微信云开发-一键快速搭建,开箱即用
后续会继续更新,敬请期待2.0全新版本欢迎添加左边的微信一起探讨!项目地址:(https://www.aliyun.com/activity/daily/bestoffer?userCodesskuuw5n)\2.Bug修复更新日历2.情侣脸功能大家不要使用了,现在阿里云的接口已经要收费了(土豪请随意),\\和注意
晴空闲云 晴空闲云
6个月前
css中box-sizing解放盒子实际宽高计算
我们知道传统的盒子模型,如果增加内边距padding和边框border,那么会撑大整个盒子,造成盒子的宽度不好计算,在实务中特别不方便。boxsizing可以设置盒模型的方式,可以很好的设置固定宽高的盒模型。盒子宽高计算假如我们设置如下盒子:宽度和高度均为200px,那么这会这个盒子实际的宽高就都是200px。但是当我们设置这个盒子的边框和内间距的时候,那
艾木酱 艾木酱
5个月前
快速入门|使用MemFire Cloud构建React Native应用程序
MemFireCloud是一款提供云数据库,用户可以创建云数据库,并对数据库进行管理,还可以对数据库进行备份操作。它还提供后端即服务,用户可以在1分钟内新建一个应用,使用自动生成的API和SDK,访问云数据库、对象存储、用户认证与授权等功能,可专
Easter79 Easter79
1年前
SpringBoot+Vue实现文件上传+预览
从松哥的微信公众号上面看到了SpringBootVue实现文件上传预览(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fmp.weixin.qq.com%2Fs%2FKi6sJbAS24OPn9YcnrZhQ)的视频教程,如下图所示:!SpringBootVue实现文件上
helloworld_28799839 helloworld_28799839
6个月前
常用知识整理
Javascript判断对象是否为空jsObject.keys(myObject).length0经常使用的三元运算我们经常遇到处理表格列状态字段如status的时候可以用到vue