vue3如何上传图片

简介: Vue3 上传图片可以使用 axios 库来发送 POST 请求,将图片上传到服务器,然后在前端展示或者保存到数据库中。

Vue3 上传图片可以使用 axios 库来发送 POST 请求,将图片上传到服务器,然后在前端展示或者保存到数据库中。


以下是一个上传图片的示例代码:


1.在模板里添加一个上传图片的表单:

<template>
  <div>
    <form @submit.prevent="uploadImage">
      <input type="file" ref="file" accept="image/*">
      <button type="submit">上传</button>
    </form>
    <img v-if="imageUrl" :src="imageUrl" alt="图片预览">
  </div>
</template>

2.在组件里处理上传图片的逻辑:

<script>
import axios from 'axios';
export default {
  data() {
    return {
      imageUrl: null,
    };
  },
  methods: {
    async uploadImage() {
      const formData = new FormData();
      formData.append('image', this.$refs.file.files[0]);
      try {
        const response = await axios.post('/api/upload', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        this.imageUrl = response.data.imageUrl;
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

3.在后端服务器代码里处理上传图片的逻辑,以下是一个使用 Node.js 和 Express 的示例:

const multer = require('multer');
const express = require('express');
const app = express();
const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    callback(null, 'uploads/');
  },
  filename: (req, file, callback) => {
    callback(null, Date.now() + '-' + file.originalname);
  },
});
const upload = multer({ storage }).single('image');
app.post('/api/upload', (req, res) => {
  upload(req, res, error => {
    if (error) {
      console.error(error);
      res.status(400).send('上传图片失败');
    } else {
      const imageUrl = `/uploads/${req.file.filename}`;
      res.send({ imageUrl });
    }
  });
});
app.listen(3000, () => {
  console.log('服务器已启动,监听端口 3000');
});

上传图片的流程大致如上。

相关文章
|
3天前
|
JavaScript 定位技术 API
在 vue3 中使用高德地图
在 vue3 中使用高德地图
9 0
|
3天前
vue3 键盘事件 回车发送消息,ctrl+回车 内容换行
const textarea = textInput.value.textarea; //获取输入框元素
13 3
|
6天前
|
JavaScript 前端开发 CDN
vue3速览
vue3速览
18 0
|
6天前
|
设计模式 JavaScript 前端开发
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
Vue3报错Property “xxx“ was accessed during render but is not defined on instance
|
6天前
|
JavaScript 前端开发 安全
Vue3官方文档速通(下)
Vue3官方文档速通(下)
16 0
|
6天前
|
JavaScript API
Vue3 官方文档速通(中)
Vue3 官方文档速通(中)
22 0
|
6天前
|
缓存 JavaScript 前端开发
Vue3 官方文档速通(上)
Vue3 官方文档速通(上)
32 0
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理
11 1
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之三:vue-router 的安装和使用
14 0
|
6天前
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
Vue3+Vite+Pinia+Naive后台管理系统搭建之二:scss 的安装和使用
12 0