文件和图像上传是许多非平凡应用程序的必备功能. 幸运的是,我们很容易在Vue应用程序中设置 vue-picture-input。
<$>[注意] 检查 这个帖子我们的如果你想创建自己的自定义文件选择器输入。
安装
通过 npm 或 Yarn安装 vue-picture-input:
1$ npm install --save vue-picture-input
2
3# or:
4$ yarn add vue-picture-input
使用
图书馆 vue-picture-input允许各种用途,并且非常简单:
1<template>
2 <picture-input
3
4 <!--Props go here-->
5
6 ></picture-input>
7</template>
以下是我们将使用的几个优惠:
- ref:我们将需要这个来访问 base64 图像字符串
- 宽度,高度: 命令组件的宽度和高度
- 接受: 用于限制被接受的文件类型
- 可移除: 指定是否可以重置组件
此外,组件会发出以下事件:
- 删除:当图像从组件 中分离时发射* 更改:当选择的图像被更改时发射(即重新选择)
以下是我们对文件输入的代码的看法:
1[label index.vue]
2<picture-input
3 ref="pictureInput"
4 @change="onChanged"
5 @remove="onRemoved"
6 :width="500"
7 :removable="true"
8 removeButtonClass="ui red button"
9 :height="500"
10 accept="image/jpeg, image/png, image/gif"
11 buttonClass="ui button primary"
12 :customStrings="{
13 upload: '<h1>Upload it!</h1>',
14 drag: 'Drag and drop your image here'}">
15
16</picture-input>
让我们添加一个按钮,允许我们将选择的图像上传到我们的后端。
它基本上在点击时呼叫试图上传方法,并具有禁用
类绑定,如果有一个选定的图像,它只会被启用:
1<button @click="attemptUpload" v-bind:class="{ disabled: !image }">
2 Upload
3</button>
接下来,我们将使用 Axios来创建网络请求,我们还将利用 Formdata API来创建发布图像数据的甜蜜构成:
1[label upload.js]
2import axios from 'axios';
3
4export default function (url, file, name = 'avatar') {
5 if (typeof url !== 'string') {
6 throw new TypeError(`Expected a string, got ${typeof url}`);
7 }
8
9 // You can add checks to ensure the url is valid, if you wish
10
11 const formData = new FormData();
12 formData.append(name, file);
13 const config = {
14 headers: {
15 'content-type': 'multipart/form-data'
16 }
17 };
18 return axios.post(url, formData, config);
19};
上面的代码接受一个 url 作为第一个参数,一个文件对象作为第二个参数,然后返回一个承诺. 它还将标题的内容类型设置为 multipart/formdata
,因此我们的后端 API 可以告诉你管道中的内容。
因此,我们可以使用上述代码:
1import FormDataPost from '/upload';
2
3//...
4
5FormDataPost('http://localhost:8001/user/picture', image)
6 .then(response=>{
7 console.log("Uploaded picture successfully");
8 })
9 .catch(err=>{
10 console.error(err);
11 });
12
13 //...
以下是我们 onChanged、 onRemoved 和 attemptUpload 方法的样子:
1//...
2
3methods: {
4 onChanged() {
5 console.log("New picture loaded");
6 if (this.$refs.pictureInput.file) {
7 this.image = this.$refs.pictureInput.file;
8 } else {
9 console.log("Old browser. No support for Filereader API");
10 }
11 },
12 onRemoved() {
13 this.image = '';
14 },
15 attemptUpload() {
16 if (this.image){
17 FormDataPost('http://localhost:8001/user/picture', this.image)
18 .then(response=>{
19 if (response.data.success){
20 this.image = '';
21 console.log("Image uploaded successfully ✨");
22 }
23 })
24 .catch(err=>{
25 console.error(err);
26 });
27 }
28 }
29}
30
31//...
完成了! 我们的图片上传在前端上工作。 Read-on 了解如何使用 Express 在 Node.js 后端上设置此功能。