Angular2:使用NG-ZORRO的upload組件對接JAVA后端實現(xiàn)上傳

環(huán)境

angular/cli:1.7.4
node:v8.11.2
ng-zorro:0.7

后端使用spring-boot做一個上傳文件的接口,前端工程上傳文件的時候?qū)雍蠖说慕涌诰涂梢粤?。下面說一下怎么使用。

新建一個Spring Boot的工程

填寫maven信息
選好web,然后下一步,finish,等待jar包下載完成
新建完成,下載好jar包,項目結(jié)構(gòu)應(yīng)該是這樣的。

啟動一下,沒什么問題開始編寫后端上傳文件的代碼

這里就不搞什么三層架構(gòu)了,就一個上傳文件,直接在web包下新建一個類FileUploadController

package com.lautumn.web;

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

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileUploadController {

    @RequestMapping("/upload")
    public Map<String, String> upload(@RequestParam("upload_file")MultipartFile file) {
        String path = "/Users/lautumn/JAVALEARN/web/upload"; // 文件保存路徑
        /**
         * 可能會出現(xiàn)重復(fù)文件,所以我們要對文件進(jìn)行一個重命名的操作
         * 截取文件的原始名稱,然后將擴(kuò)展名和文件名分開,使用:時間戳-文件名.擴(kuò)展名的格式保存
         */
        // 獲取文件名稱
        String fileName = file.getOriginalFilename();
        // 獲取擴(kuò)展名
        String fileExtensionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 獲取文件名
        String name = fileName.substring(0, fileName.lastIndexOf("."));
        // 生成最終保存的文件名,格式為: 時間戳-文件名.擴(kuò)展名
        String id = String.valueOf(new Date().getTime());
        String saveFileName = id + "-" + name + "." + fileExtensionName;
        /**
         * 上傳操作:可能upload目錄不存在,所以先判斷一下如果不存在,那么新建這個目錄
         */
        File fileDir = new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        /**
         * 上傳
         */
        File targetFile = new File(path, saveFileName);
        try {
            file.transferTo(targetFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        /**
         * 返回值,這三個對象是ng-zorro那邊需要的
         */
        Map<String, String> result = new HashMap<>();
        result.put("url", String.format("http://localhost:8080/upload/%s", saveFileName));
        result.put("uid", id);
        result.put("name", fileName);
        return result;
    }
}

說明:注釋都有,如果不知道上傳路徑怎么寫就在項目目錄下右鍵copy一下路徑填上就好了。


image.png

然后在resource/static 下新建一個index.html 測試一下上傳是否成功。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="upload_file">
    <button type="submit">上傳</button>
</form>
</body>
</html>

啟動項目訪問localhost:8080/index.html


image.png
選擇一個文件然后點擊上傳
文件也靜靜的躺在它該在的地方

這時候點擊鏈接是訪問不到的,因為還沒有配置靜態(tài)資源訪問路徑。


配置application.yml

這時候重啟項目再次上傳文件的操作,點擊返回的url應(yīng)該可以了。

這里還有一個問題,因為我們是前后端分離的,待會前端項目啟動端口肯定不能和后端的一樣,所以會有跨域的問題,


添加上這個注解就可以了
那么接下來是前端的事情,這里就不詳細(xì)說搭建項目過程了,這里采用的NG-ZORRO的版本是0.7x,給個官網(wǎng)鏈接,按照官網(wǎng)示例搭建項目https://ng.ant.design/version/0.7.x/docs/getting-started/zh

拷貝一段ng-zorro的uoload示例

  • app.component.ts
import { Component } from '@angular/core';
import {NzMessageService, UploadFile} from 'ng-zorro-antd';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  fileList = [
    {
      uid: -1,
      name: 'xxx.png',
      status: 'done',
      url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }
  ];
  previewImage = '';
  previewVisible = false;

  constructor(private msg: NzMessageService) {}

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }
}

  • app.component.html
<nz-upload
  nzAction="https://jsonplaceholder.typicode.com/posts/"
  nzListType="picture-card"
  [(nzFileList)]="fileList"
  [nzShowButton]="fileList.length < 3"
  [nzPreview]="handlePreview">
  <i class="anticon anticon-plus"></i>
  <div class="ant-upload-text">Upload</div>
</nz-upload>
<nz-modal [nzVisible]="previewVisible" [nzContent]="modalContent" [nzFooter]="null" (nzOnCancel)="previewVisible=false">
  <ng-template #modalContent>
    <img [src]="previewImage" [ngStyle]="{ 'width': '100%' }" />
  </ng-template>
</nz-modal>

啟動angular工程,頁面展示


image.png

這時候?qū)游覀儗懙暮蠖松蟼魑募恕?br> 首先在app.component.html里將nzAction修改為我們寫的后端地址


image.png

這時候問題來了,我們后端的上傳邏輯需要傳一個名字為upload_file的參數(shù),這個要怎么辦呢?
查看官網(wǎng)得知,可以使用nzName來指定上傳文件的參數(shù)


image.png

這時候兩個項目啟動起來,測試上傳


第二張是我上傳的,控制臺也沒報什么錯誤

這里有一個問題,有時候點擊上傳的時候會出現(xiàn)文件上傳中,但是縮略圖沒出來


image.png

查看后臺發(fā)現(xiàn)文件已經(jīng)到后臺了,這時候可以點擊一下其他圖片的預(yù)覽,或者點擊一下上傳的按鈕再關(guān)閉試試


image.png

圖片就出來了

具體原因我也不太清楚,但是在后端工程中上傳的時候睡眠1秒左右,或者在Chrome瀏覽器的網(wǎng)速調(diào)整至3g就可以保證每次都會出預(yù)覽圖,我覺得可能是本地開發(fā)中上傳文件速度太快還是怎么樣,沒能檢測到吧。如果有哪位知道真實原因麻煩告知一下,以及解決辦法,畢竟上傳文件的時候睡眠一秒,不是很合理,如果是在真實線上環(huán)境應(yīng)該沒問題吧,可能原因還是上傳的速度太快沒檢測到,如果在真實線上環(huán)境,有網(wǎng)絡(luò)的延遲應(yīng)該是可以每次都出預(yù)覽圖的。具體我沒有試驗過。僅猜測。有解決方法的還請告知我一聲,感激。

以上就完成了。

源碼
https://github.com/Ariesssssssss/ng-zorro-upload

最后編輯于
?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

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