SpringBoot+Vue.js前後端分離實現大檔案分塊上傳

逗貓攻城獅發表於2019-03-01

原文地址: luoliangDSGA's blog
部落格地址: luoliangdsga.github.io
歡迎轉載,轉載請註明作者及出處,謝謝!

SpringBoot+Vue.js前後端分離實現大檔案分塊上傳

之前寫過一篇SpringBoot+Vue前後端分離實現檔案上傳的部落格,但是那篇部落格主要針對的是小檔案的上傳,如果是大檔案,一次性上傳,將會出現不可預期的錯誤。所以需要對大檔案進行分塊,再依次上傳,這樣處理對於伺服器容錯更好處理,更容易實現斷點續傳、跨瀏覽器上傳等功能。本文也會實現斷點,跨瀏覽器繼續上傳的功能。

開始

GIF效果預覽

SpringBoot+Vue.js前後端分離實現大檔案分塊上傳
此處用到了這位大佬的Vue上傳元件,此圖也是引用自他的GitHub,感謝這位大佬。

需要準備好基礎環境

  • Java
  • Node
  • MySQL

準備好這些之後,就可以往下看了。

後端

新建一個SpringBoot專案,我這裡使用的是SpringBoot2,引入mvc,jpa,mysql相關的依賴。

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
        </dependency>
    </dependencies>
複製程式碼

在yml中配置mvc以及資料庫連線等屬性

server:
  port: 8081
  servlet:
    path: /boot

spring:
  servlet:
    multipart:
      max-file-size: 20MB
      max-request-size: 20MB
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    properties:
      hibernate:
        hbm2ddl:
          auto: create-drop
    show-sql: true

logging:
  level:
    org.boot.uploader.*: debug

prop:
  upload-folder: files
複製程式碼

定義檔案上傳相關的類,一個是FileInfo,代表檔案的基礎資訊;一個是Chunk,代表檔案塊。

FileInfo.java

@Data
@Entity
public class FileInfo implements Serializable {
    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String filename;

    @Column(nullable = false)
    private String identifier;

    @Column(nullable = false)
    private Long totalSize;

    @Column(nullable = false)
    private String type;

    @Column(nullable = false)
    private String location;
}
複製程式碼

Chunk.java

@Data
@Entity
public class Chunk implements Serializable {
    @Id
    @GeneratedValue
    private Long id;
    /**
     * 當前檔案塊,從1開始
     */
    @Column(nullable = false)
    private Integer chunkNumber;
    /**
     * 分塊大小
     */
    @Column(nullable = false)
    private Long chunkSize;
    /**
     * 當前分塊大小
     */
    @Column(nullable = false)
    private Long currentChunkSize;
    /**
     * 總大小
     */
    @Column(nullable = false)
    private Long totalSize;
    /**
     * 檔案標識
     */
    @Column(nullable = false)
    private String identifier;
    /**
     * 檔名
     */
    @Column(nullable = false)
    private String filename;
    /**
     * 相對路徑
     */
    @Column(nullable = false)
    private String relativePath;
    /**
     * 總塊數
     */
    @Column(nullable = false)
    private Integer totalChunks;
    /**
     * 檔案型別
     */
    @Column
    private String type;
    @Transient
    private MultipartFile file;
}
複製程式碼

編寫檔案塊相關的業務操作

@Service
public class ChunkServiceImpl implements ChunkService {
    @Resource
    private ChunkRepository chunkRepository;

    @Override
    public void saveChunk(Chunk chunk) {
        chunkRepository.save(chunk);
    }

    @Override
    public boolean checkChunk(String identifier, Integer chunkNumber) {
        Specification<Chunk> specification = (Specification<Chunk>) (root, criteriaQuery, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("identifier"), identifier));
            predicates.add(criteriaBuilder.equal(root.get("chunkNumber"), chunkNumber));

            return criteriaQuery.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };

        return chunkRepository.findOne(specification).orElse(null) == null;
    }

}
複製程式碼
  1. checkChunk()方法會根據檔案唯一標識,和當前塊數判斷是否已經上傳過這個塊。
  2. 這裡只貼了ChunkService的程式碼,其他的程式碼只是jpa簡單的存取。

接下來就是編寫最重要的controller了

@RestController
@RequestMapping("/uploader")
@Slf4j
public class UploadController {
    @Value("${prop.upload-folder}")
    private String uploadFolder;
    @Resource
    private FileInfoService fileInfoService;
    @Resource
    private ChunkService chunkService;

    @PostMapping("/chunk")
    public String uploadChunk(Chunk chunk) {
        MultipartFile file = chunk.getFile();
        log.debug("file originName: {}, chunkNumber: {}", file.getOriginalFilename(), chunk.getChunkNumber());

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(generatePath(uploadFolder, chunk));
            //檔案寫入指定路徑
            Files.write(path, bytes);
            log.debug("檔案 {} 寫入成功, uuid:{}", chunk.getFilename(), chunk.getIdentifier());
            chunkService.saveChunk(chunk);

            return "檔案上傳成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "後端異常...";
        }
    }

    @GetMapping("/chunk")
    public Object checkChunk(Chunk chunk, HttpServletResponse response) {
        if (chunkService.checkChunk(chunk.getIdentifier(), chunk.getChunkNumber())) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        }

        return chunk;
    }

    @PostMapping("/mergeFile")
    public String mergeFile(FileInfo fileInfo) {
        String path = uploadFolder + "/" + fileInfo.getIdentifier() + "/" + fileInfo.getFilename();
        String folder = uploadFolder + "/" + fileInfo.getIdentifier();
        merge(path, folder);
        fileInfo.setLocation(path);
        fileInfoService.addFileInfo(fileInfo);

        return "合併成功";
    }
}
複製程式碼
  1. 文章開頭就提到了前後端分離,既然是前後端分離,肯定會涉及到跨域問題,在上一篇文章中是通過springMVC的@CrossOrigin註解來解決跨域問題,這裡並沒有使用這個註解,在下面的前端專案中會使用一個node的中介軟體來做代理,解決跨域的問題。
  2. 可以看到有兩個/chunk路由,第一個是post方法,用於上傳並儲存檔案塊,需要對檔案塊名進行編號,再儲存在指定路徑下;第二個是get方法,前端上傳之前會先進行檢測,如果此檔案塊已經上傳過,就可以實現斷點和快傳。
  3. /mergeFile用於合併檔案,在所有塊上傳完畢後,前端會呼叫此介面進行制定檔案的合併。其中的merge方法是會遍歷指定路徑下的檔案塊,並且按照檔名中的數字進行排序後,再合併成一個檔案,否則合併後的檔案會無法使用,程式碼如下:
public static void merge(String targetFile, String folder) {
        try {
            Files.createFile(Paths.get(targetFile));
            Files.list(Paths.get(folder))
                    .filter(path -> path.getFileName().toString().contains("-"))
                    .sorted((o1, o2) -> {
                        String p1 = o1.getFileName().toString();
                        String p2 = o2.getFileName().toString();
                        int i1 = p1.lastIndexOf("-");
                        int i2 = p2.lastIndexOf("-");
                        return Integer.valueOf(p2.substring(i2)).compareTo(Integer.valueOf(p1.substring(i1)));
                    })
                    .forEach(path -> {
                        try {
                            //以追加的形式寫入檔案
                            Files.write(Paths.get(targetFile), Files.readAllBytes(path), StandardOpenOption.APPEND);
                            //合併後刪除該塊
                            Files.delete(path);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
複製程式碼

到這裡,後端主要的邏輯已經寫完了,下面開始編寫前端的部分。

前端

前端我直接clone了vue-uploader,在這個程式碼的基礎上進行了修改。

App.vue

<template>
  <uploader :options="options" :file-status-text="statusText" class="uploader-example" ref="uploader"
            @file-complete="fileComplete" @complete="complete"></uploader>
</template>

<script>
  import axios from 'axios'
  import qs from 'qs'

  export default {
    data() {
      return {
        options: {
          target: '/boot/uploader/chunk',
          testChunks: true,
          simultaneousUploads: 1,
          chunkSize: 10 * 1024 * 1024
        },
        attrs: {
          accept: 'image/*'
        },
        statusText: {
          success: '成功了',
          error: '出錯了',
          uploading: '上傳中',
          paused: '暫停中',
          waiting: '等待中'
        }
      }
    },
    methods: {
      // 上傳完成
      complete() {
        console.log('complete', arguments)
      },
      // 一個根檔案(資料夾)成功上傳完成。
      fileComplete() {
        console.log('file complete', arguments)
        const file = arguments[0].file;
        axios.post('/boot/uploader/mergeFile', qs.stringify({
          filename: file.name,
          identifier: arguments[0].uniqueIdentifier,
          totalSize: file.size,
          type: file.type
        })).then(function (response) {
          console.log(response);
        }).catch(function (error) {
          console.log(error);
        });
      }
    },
    mounted() {
      this.$nextTick(() => {
        window.uploader = this.$refs.uploader.uploader
      })
    }
  }
</script>
...
複製程式碼

配置說明:

  1. target 目標上傳 URL,可以是字串也可以是函式,如果是函式的話,則會傳入 Uploader.File 例項、當前塊 Uploader.Chunk 以及是否是測試模式,預設值為 '/'。
  2. chunkSize 分塊時按照該值來分。最後一個上傳塊的大小是可能是大於等於1倍的這個值但是小於兩倍的這個值大小,預設 110241024。
  3. testChunks 是否測試每個塊是否在服務端已經上傳了,主要用來實現秒傳、跨瀏覽器上傳等,預設true。
  4. simultaneousUploads 併發上傳數,預設3。

更多說明請直接參考vue-uploader

解決跨域問題

這裡使用了http-proxy-middleware這個node中介軟體,可以對前端的請求進行轉發,轉發到指定的路由。

在index.js中進行配置,如下:

dev: {
    env: require('./dev.env'),
    port: 8080,
    autoOpenBrowser: true,
    assetsSubDirectory: '',
    assetsPublicPath: '/',
    proxyTable: {
      '/boot': {
        target: 'http://localhost:8081',
        changeOrigin: true  //如果跨域,則需要配置此項
      }
    },
    // CSS Sourcemaps off by default because relative paths are "buggy"
    // with this option, according to the CSS-Loader README
    // (https://github.com/webpack/css-loader#sourcemaps)
    // In our experience, they generally work as expected,
    // just be aware of this issue when enabling this option.
    cssSourceMap: false
  }
複製程式碼

proxyTable表示代理配置表,將特定的請求代理到指定的API介面,這裡是將'localhost:8080/boot/xxx'代理到'http://localhost:8081/boot/xxx'。

現在可以開始驗證了,分別啟動前後端的專案

  • 前端
npm install
npm run dev
複製程式碼
  • 後端 可以通過command line,也可以直接執行BootUploaderApplication的main()方法

執行效果就像最開始的那張圖,可以同時上傳多個檔案,上傳暫停之後更換瀏覽器,選擇同一個檔案可以實現繼續上傳的效果,大家可以自行進行嘗試,程式碼會在我的GitHub上進行更新。

最後

整篇文章到這裡差不多就結束了,這個專案可以作為demo用來學習,有很多可以擴充套件的地方,肯定也會有不完善的地方,有更好的方法也希望能指出,共同交流學習。

相關文章