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

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

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

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

error

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

result2

創(chuàng)建SpringBoot項目

pom.xml文件

使用IDEA創(chuàng)建一個基于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目錄下創(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">點擊上傳</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文件中增加幾個配置,如下:

#配置文件傳輸
spring.servlet.multipart.enabled =true
spring.servlet.multipart.file-size-threshold =0
#設(shè)置單個文件上傳的數(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項目

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

從碼云上獲取fileupload項目

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

參考資料

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容