SpringBoot+Vue實(shí)現(xiàn)文件上傳+預(yù)覽

從松哥的微信公眾號(hào)上面看到了SpringBoot+Vue實(shí)現(xiàn)文件上傳+預(yù)覽的視頻教程嗦嗡,如下圖所示:

SpringBoot+Vue實(shí)現(xiàn)文件上傳示例

跟著做氛魁,使用IDEA一遍看一邊做赐写,沒想到由于自己馬虎將日期SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd/");寫成了SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy/MM/dd");導(dǎo)致后續(xù)拼接文件名出錯(cuò):

error

由于在本地地址生成pdf文件失敗導(dǎo)致無法實(shí)現(xiàn)預(yù)覽PDF文件的效果恩闻。
最后將日期格式修改后成功上傳并且可以實(shí)現(xiàn)pdf文件預(yù)覽右蒲。
result1

result2

創(chuàng)建SpringBoot項(xiàng)目

pom.xml文件

使用IDEA創(chuàng)建一個(gè)基于SpringBoot的項(xiàng)目,依賴選擇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>

添加一個(gè)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<>();

        // 得到上傳時(shí)的文件名
        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目錄下創(chuàng)建index.html骇扇,并且引入vue.js和elment-ui,具體可以參考Element-UI安裝
對應(yīng)的頁面內(nèi)容如下圖所示:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" >
</head>
<body>
<div id="app">
    <el-upload
        action="/upload"
        :on-preview="handlePreview"
        multiple
        :limit="10"
        accept=".pdf">
        <el-button size="small" type="primary">點(diǎn)擊上傳</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組件,如下所示:

el-upload

需要注意的問題

SpringBoot上傳文件的大小限制

SpringBoot對于上傳的文件大小有限制少孝,所以需要在application.properties文件中增加幾個(gè)配置继低,如下:

#配置文件傳輸
spring.servlet.multipart.enabled =true
spring.servlet.multipart.file-size-threshold =0
#設(shè)置單個(gè)文件上傳的數(shù)據(jù)大小
spring.servlet.multipart.max-file-size = 100MB
#設(shè)置總上傳的數(shù)據(jù)大小
spring.servlet.multipart.max-request-size=100MB

我這里設(shè)置單文件上傳的最大大小為100MB和總共文件的大小為100MB

最終源代碼下載

相關(guān)代碼我已經(jīng)上傳至我的Github和Gitee碼云倉庫上面了,需要的話可自行獲取

從github上面克隆fileupload項(xiàng)目

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

從碼云上獲取fileupload項(xiàng)目

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

參考資料

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末袁翁,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子婿脸,更是在濱河造成了極大的恐慌粱胜,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件狐树,死亡現(xiàn)場離奇詭異焙压,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)抑钟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進(jìn)店門涯曲,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人在塔,你說我怎么就攤上這事幻件。” “怎么了心俗?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我城榛,道長揪利,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任狠持,我火速辦了婚禮疟位,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘喘垂。我一直安慰自己甜刻,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布正勒。 她就那樣靜靜地躺著得院,像睡著了一般。 火紅的嫁衣襯著肌膚如雪章贞。 梳的紋絲不亂的頭發(fā)上祥绞,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天,我揣著相機(jī)與錄音鸭限,去河邊找鬼蜕径。 笑死,一個(gè)胖子當(dāng)著我的面吹牛败京,可吹牛的內(nèi)容都是我干的兜喻。 我是一名探鬼主播,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼赡麦,長吁一口氣:“原來是場噩夢啊……” “哼朴皆!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起隧甚,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤车荔,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后戚扳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體忧便,經(jīng)...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年帽借,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了珠增。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,731評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡砍艾,死狀恐怖蒂教,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情脆荷,我是刑警寧澤凝垛,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布懊悯,位于F島的核電站,受9級特大地震影響梦皮,放射性物質(zhì)發(fā)生泄漏炭分。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一剑肯、第九天 我趴在偏房一處隱蔽的房頂上張望捧毛。 院中可真熱鬧,春花似錦让网、人聲如沸呀忧。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽而账。三九已至,卻和暖如春丸凭,著一層夾襖步出監(jiān)牢的瞬間福扬,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工惜犀, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留铛碑,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓虽界,卻偏偏與公主長得像汽烦,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子莉御,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,629評論 2 354