fastdfs 上傳圖片

前言

在做項目時,有這樣一個需求用戶可以上傳自己本地的圖片,這就利用到了fastdfs,什麼是fastdfs呢,官話是這樣說的:FastDFS是一個開源的輕量級分佈式文件系統,它對文件進行管理,功能包括:文件存儲、文件同步、文件訪問(文件上傳、文件下載)等,解決了大容量存儲和負載均衡的問題
下面說一下在前後端怎麼使用fastdsf來上傳圖片

後端代碼

後端用的是spring boot 下面是關鍵代碼

controller

    @ApiOperation(value = "上傳圖片到fastdfs")
    @PostMapping(value = "/upLoad")
    public ItooResult upLoad(@RequestBody MultipartFile multfile) {
        try {
            String url = wordOtherService.upLoadPicture(multfile);
            return ItooResult.build("0000","上傳成功",url );
        } catch (Exception e) {
            return ItooResult.build("1111", "上傳失敗");
        }
    }

service

   		@Resource
    	private FastFileStorageClient fastFileStorageClient;

		StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        String serverPath = trackerClient.getStoreStorage("group2").getIp();
        imagePath = "http://" + serverPath + "/" + storePath.getFullPath();
        return imagePath;

還有一些在yml文件中的配置,文件上傳大小限制,格式限制,網上有很多優秀的博客可以借鑑

前端代碼

前端用的是ionic框架,這裏也是說一些主要的代碼

  1. Html頁
 <input style="margin-top: 15%; display:none;" #file type="file" id="file" ng2FileSelect [uploader]="uploader" accept="image/*" (change)="selectedFileOnChanged(file)">
  1. 引用FileUploader
import { FileUploader } from 'ng2-file-upload';
  1. 初始化FileUploader
  public uploader: FileUploader = new FileUploader({
    // 聲明一個FileUploader類型的變量,並將其初始化
    url: 'http://localhost:8090/english-web/word/upLoad',
    method: 'POST',
    removeAfterUpload: true,
    itemAlias: 'multfile',
  });
  1. 上傳圖片
  public selectedFileOnChanged(file: HTMLInputElement) {
    this.uploader.onBeforeUploadItem = (item => {
      item.withCredentials = false;
    });
    this.uploadPhoto();
  }
  uploadPhoto() {
    // 開始上傳
    this.uploader.queue[0].upload();
    this.uploader.queue[0].onSuccess = function (response, status, headers) {
      if (status === 200) {
      } else {
        alert('上傳圖片失敗');
      }
   };
  }

效果展示/table>

在這裏插入圖片描述

我們也可以通過url去訪問圖片
在這裏插入圖片描述

至此一個簡單的上傳圖片就ok了 ,希望對你有幫助!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章