7

手把手教你用 Vue 搭建带预览的「上传图片」管理后台

 2 years ago
source link: https://studygolang.com/articles/35548
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue 搭建带预览的「上传图片」管理后台

本文首发:《Vue 搭建带预览的「上传图片」管理后台

手把手教你开发带预览的 Vue 图片上传组件,即图片上传管理后台。只要你跟本教程一步一步走,最终能很好的理解整个前后端传图的工程逻辑。前端我们使用 Vue + Axios + Multipart 来搭建前端上传图片应用,后端我们使用 Node.js + Express + Multer 来搭建后端上传图片的后端处理。

本教程还会教给大家如何写一个可限制上传图片大小,有进度条,可报错,可显示图片列表,可下载已上传图片的图片管理后台。

最后完成的上传图片工具后台如下图,跟随本教学习,你也可以搭出来。

vue-uploads

如果你对前端不是很熟悉,不想写前端,推荐使用卡拉云搭建后台管理系统,卡拉云是新一代低代码开发工具,不用懂任何前端技术,仅靠鼠标拖拽,即可快速搭建包括「图片上传」在内的任何后台管理工具。立即试用卡拉云 1 分钟搭建「图片上传」工具。详情见本文文末。

Vue + Node.js「图片上传」前后端项目结构

vue-nodejs

Vue 前端部分

  • UploadFilesService.js:这个脚本调用通过 Axios 保存文件和获取文件的方法
  • UploadFiles.vue:这个组件包含所有图片上传相关的信息和操作
  • App.vue:把我们的组件导入到 Vue 起始页
  • index.html:用于导入 Bootstrap
  • http-common.js:配置并初始化 Axios
  • vue.config.js:配置 APP 端口

Node.js 后端部分

  • resources/static/assets/uploads:用于存储上传的文件
  • middleware/upload.js:初始化 Multer 引擎并定义中间件
  • file.controller.js:配置 Rest API
  • routes/index.js:路由,定义前端请求后端如何执行
  • server.js:运行Node.js Express 应用

✦ 前端部分 - Vue + Vue 图片上传组件 + Axios + Multipart

配置 Vue 环境

使用 npm 安装 Vue 脚手架 vue-cli

npm install -g @vue/cli

然后我们创建一个 Vue 项目 kalacloud-vue-upload-image

vue create kalacloud-vue-upload-image

安装完成后,cd 进入 kalacloud-vue-upload-image 目录,接下来所有操作都在这个目录之下。

安装 Axios:

npm install axios

我们先跑一下 Vue ,这是 vue 的默认状态

npm run serve

我们可以看到浏览器里 Vue 已经在 localhost:8080 跑起来了。

扩展阅读:《Video.js 使用教程 - 手把手教你基于 Vue 搭建 HTML 5 视频播放器

导入 Bootstrap 到项目中

打开 index.html 把以下代码添加到 中:

文件位置:public/index.html

<!DOCTYPE html>
<html lang="en"><head>
    ...
    <link type="text/css" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" /></head>
  ...
</html>

初始化 Axios HTTP 客户端

在 src 文件夹下,创建 http-common.js 文件,如下所示:

文件位置:src/http-common.js

import axios from "axios";
export default axios.create({
  baseURL: "http://localhost:8080",
  headers: {
    "Content-type": "application/json"
  }
});

请记住更改baseURL,它取决于您的服务器配置的 REST API 网址。

扩展阅读:《12 款最棒 Vue 开源 UI 库测评 - 特别针对国内使用场景推荐

创建「上传图片」功能

我们来写一个 JS 脚本,这个脚本调用 Axios 发送 HTTP API 请求,与后端服务器通讯。

这个脚本包含 2 个功能

  • upload(file): POST 数据到后端,再加一个上传进度的回调,可以放个上传进度条。
  • getFiles(): 用于获取服务器图片上传夹中的文件列表

文件位置:src/services/UploadFilesService.js

import http from "../http-common";
class UploadFilesService {
  upload(file, onUploadProgress) {
    let formData = new FormData();
    formData.append("file", file);
    return http.post("/upload", formData, {
      headers: {
        "Content-Type": "multipart/form-data"
      },
      onUploadProgress
    });
  }
  getFiles() {
    return http.get("/files");
  }
}
export default new UploadFilesService();
  • 首先导入我们刚刚写好的 Axios HTTP 配置文件 http-common.js
  • FormData 是一种可将数据编译成键值对的数据结构
  • Axios的进度条事件,onUploadProgress 是用来监测上传进度,显示进度信息
  • 最后我们调用 Axios 提供的 post()&get() 来向后端 API 发送 POST & GET 请求

扩展阅读:《顶级好用的 8 款 Vue 弹窗组件测评与推荐

创建一个 Vue 图片上传组件

让我们创建一个带有进度条、卡片、按钮和消息的图像上传 UI。

首先我们创建一个 Vue 组件模板并导入UploadFilesService

文件位置:src/components/UploadFiles.vue

接下来,我们来写一个 Vue 图片上传组件,这个组件要包含上传图片的所有基本功能,比如 上传按钮、进度条、图片预览、提示信息、基本 UI 等。

首先,创建一个 Vue 组件模版(UploadFiles.vue)然后把刚刚写好的配置文件(UploadFilesService.js)导入进去。

文件位置:src/components/UploadFiles.vue

<template>
</template>
<script>
import UploadService from "../services/UploadFilesService";
export default {
  name: "upload-image",
  data() {
    return {
    };
  },
  methods: {

  }
};
</script>

然后在这里定义 data() 变量

// src/components/UploadFiles.vue

export default {
  name: "upload-files",
  data() {
    return {
      selectedFiles: undefined,
      progressInfos: [],
      message: "",
      fileInfos: [],
    };
  },
};

接下来,我们定义 methodsselectImage()ref="file” 中获取选定的文件。

// src/components/UploadFiles.vue

export default {
  name: "upload-image",
  ...
  methods: {
    selectImage() {
      this.currentImage = this.$refs.file.files.item(0);
      this.previewImage = URL.createObjectURL(this.currentImage);
      this.progress = 0;
      this.message = "";
    },
  }
};

我们读取 currentImage 作为 image 的输入参数。用 URL.createObjectURL() 静态方法来获取图像预览的 URL 存入 previewImage,方法会创建一个 [DOMString](https://developer.mozilla.org/zh-CN/docs/Web/API/DOMString) ,其中包含一个表示参数中提供的对象的URL。这个 URL 的生命周期和创建它的窗口中的 [document](https://developer.mozilla.org/zh-CN/docs/Web/API/Document) 绑定。

最后,我们还定义了 upload() 上传图片的方法,如下所示:

// src/components/UploadFiles.vue

export default {
  name: "upload-image",
  ...
  methods: {
    ...
    upload() {
      this.progress = 0;
      UploadService.upload(this.currentImage, (event) => {
        this.progress = Math.round((100 * event.loaded) / event.total);
      })
        .then((response) => {
          this.message = response.data.message;
          return UploadService.getFiles();
        })
        .then((images) => {
          this.imageInfos = images.data;
        })
        .catch((err) => {
          this.progress = 0;
          this.message = "Could not upload the image! " + err;
          this.currentImage = undefined;
        });
    },
  }
};

图片的上传进度根据 event.loadedevent.total 来计算。如果图片上传成功,我们调用 UploadService.getFiles() 来获取图片信息并把结果分赋值给 imageInfos

imageInfos 是一个 {name, url} 对象数组。接着我们把它加到 mounted() 中,让它可以执行。

export default {
  name: "upload-image",
  ...
  mounted() {
    UploadService.getFiles().then(response => {
      this.imageInfos= response.data;
    });
  }
};

现在我们实现上传图片 UI 的 HTML 模板。将以下内容添加到


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK