vue2+element-ui+nodejs實現(xiàn)圖片上傳和修改圖片到數(shù)據(jù)庫的方法
記錄一下在做項目過程中實現(xiàn)圖片保存到數(shù)據(jù)庫,并且可以修改圖片的功能
先來說說怎么簡單實現(xiàn)圖片上傳到服務(wù)器這個功能
文件夾擺放
nodejs部分
先在app文件夾的創(chuàng)建index.js,在其中定義一個路由(為了更好的模塊化處理,直接用app.post也行)
const express = require('express') const app = express() const cors = require('cors') const port = 3001 app.use(cors()) app.use(express.urlencoded({ extended: false })) app.use(express.json()) /* 使用圖片路由 */ const imgRouter = require("../router/images.js"); app.use("/api", imgRouter);
然后在router文件夾中創(chuàng)建一個images.js
其中代碼如下
const express = require("express"); const router = express.Router(); // 引入multer const multer = require("multer") const fs=require("fs") //導(dǎo)入數(shù)據(jù)庫 const db = require("../database/index"); //圖片上傳 router.post( "/imgload", multer({ //設(shè)置文件存儲路徑 dest: "public/images", }).array("file", 1), function (req, res, next) { console.log(req.body,"req.bodyreq.bodyreq.bodyreq.body"); let files = req.files; let file = files[0]; let fileInfo = {}; file.originalname = Buffer.from(file.originalname, "latin1").toString( "utf8" ); let path = "public/images/" + Date.now().toString() + file.originalname; fs.renameSync("./public/images/" + file.filename, path); console.log(path); db.query() //獲取文件基本信息 fileInfo.type = file.mimetype; fileInfo.name = file.originalname; fileInfo.size = file.size; fileInfo.path = path; res.send({ code: 200, msg: "OK", data: fileInfo, }); } ) module.exports = router;
其中代碼中有設(shè)置文件存儲路徑dest: "public/images",這個文件夾你可以先創(chuàng)建也可以不創(chuàng)建,他會自動幫你創(chuàng)建,他接收的圖片會在app文件夾中顯示出來,如果報錯沒有此文件夾,你可以先創(chuàng)建
vue部分
使用element-ui中的Upload 上傳組件,我的版本是2.8.2
<template> <div> <el-upload class="upload-demo" ref="upload" action='http://localhost:3001/api/imgload' :data="form" :on-preview="handlePreview" :auto-upload="false" :on-success="handleUploadSuccess" > <el-button slot="trigger" size="small" type="primary" >選取文件</el-button > <div slot="tip" class="el-upload__tip"> 只能上傳jpg/png文件,且不超過500kb </div> </el-upload> <el-button type="primary" @click="submit">確 定</el-button> </div> </template> export default{ methods:{ submit(){ this.$refs.upload.submit(); } } }
其中action是后端接口圖片上傳修改都可以通過這個接口處理,點擊確定按鈕,圖片就會上傳到服務(wù)器,還可以設(shè)置成功上傳的回調(diào)函數(shù),這個具體查看官網(wǎng)說明文檔
這時候我們可以看到后端控制臺中有上傳的文件路徑
?和在public/images有如下圖片,圖片名字為什么這么奇怪,因為代碼中加上了時間戳函數(shù),你也可以加上自己的東西。
自此,我們完成了圖片上傳到服務(wù)器的方法
接下來我們怎么把圖片插入數(shù)據(jù)庫呢,在這里我的方法是把圖片名稱和后綴加入的數(shù)據(jù)庫中(這個方法有局限性,后期如果遇到好點的方法再更新,現(xiàn)在先來實現(xiàn)效果)
在images.js我們遺留下了一個db.query(),這個是用來執(zhí)行數(shù)據(jù)庫語句的,先在app數(shù)據(jù)庫下創(chuàng)建images表
?在database的index.js文件中我們定義數(shù)據(jù)庫,xxx為你自己的數(shù)據(jù)庫屬性
const mysql = require("mysql"); const db = mysql.createPool({ host: "xxxx", user: "xxx", password: "xxx", database: "app", multipleStatements: true }) module.exports = db;
配置好后,我們在image.js中加入數(shù)據(jù)庫語句,images.js代碼更新如下
const express = require("express"); const router = express.Router(); // 引入multer const multer = require("multer") const fs=require("fs") //導(dǎo)入數(shù)據(jù)庫 const db = require("../database/index"); //圖片上傳 router.post( "/imgload", multer({ //設(shè)置文件存儲路徑 dest: "public/images", }).array("file", 1), function (req, res, next) { console.log(req.body,"req.bodyreq.bodyreq.bodyreq.body"); let files = req.files; let file = files[0]; let fileInfo = {}; file.originalname = Buffer.from(file.originalname, "latin1").toString( "utf8" ); let path = "public/images/" + Date.now().toString() + file.originalname; fs.renameSync("./public/images/" + file.filename, path); console.log(path); let sql=`insert into images (imagesname) VALUES ('${path}');` db.query(sql) //獲取文件基本信息 fileInfo.type = file.mimetype; fileInfo.name = file.originalname; fileInfo.size = file.size; fileInfo.path = path; res.send({ code: 200, msg: "OK", data: fileInfo, }); } ) module.exports = router;
在前端頁面提交圖片,刷新數(shù)據(jù)庫,效果如下
自此我們完成了,圖片路徑存放數(shù)據(jù)庫的操作
接下來說說在項目中經(jīng)常使用到的功能就是上傳圖片的
如何修改圖片?
先來說說我的實現(xiàn)思路吧,前面我們已經(jīng)實現(xiàn)了圖片上傳和存放數(shù)據(jù)庫的功能,一般我們把圖片和用戶的唯一標(biāo)識(用戶編號)放在一個表里面,這樣我們可以通過sql的updata語句來實現(xiàn)修改用戶的圖片的操作。
那怎么把圖片顯示到用戶的界面呢?
通過掛載靜態(tài)資源路徑訪問服務(wù)器的文件夾,前面上傳圖片時候服務(wù)器創(chuàng)建了public/images文件夾,在里面存放了我們上傳的圖片,在前端里面我們可以通過拼接src路徑來實現(xiàn)圖片的顯示。假如你上傳的圖片攜帶了參數(shù)如用戶編號(如何攜帶參數(shù),element-ui的Upload組件有說明),我們可以重寫一下存放到數(shù)據(jù)庫的圖片名稱
在images.js執(zhí)行sql語句之前可以加上以下語句
let imgName=req.body.userId+fileInfo.name
這樣我們就可以獲得,如123圖像.jpg的圖片路徑存放到數(shù)據(jù)庫
使用nodejs的express進(jìn)行靜態(tài)資源掛載
app.use("/api/images", express.static("./public/images")); app.get("/api/images/:filename", (req, res) => { const filename = req.params.filename; const imagePath = path.join(__dirname, "public/images", filename); fs.access(imagePath, fs.constants.F_OK, (error) => { if (error) { // 圖片不存在,返回404狀態(tài)碼 res.status(404).send("圖片不存在"); } else { // 圖片存在 res.status(200).send("圖片存在"); } }); });
在前端獲取圖片可以src動態(tài)拼接
<img :src="掛載靜態(tài)資源路徑 + 請求回來帶圖片的數(shù)據(jù)名稱" style="width: 100%;height: 100%;"/>
掛載靜態(tài)資源路徑即上面代碼中的/api/images,通過http://api/imageshttp://127.0.0.1//123.png即可訪問到圖片,前端請求只需要把圖片名稱返回即可。
如果有更加好的方法可以和我交流一下,我這個屬于笨方法,哈哈哈
總結(jié)
到此這篇關(guān)于vue2+element-ui+nodejs實現(xiàn)圖片上傳和修改圖片到數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)vue2圖片上傳和修改圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
element-ui 表格數(shù)據(jù)時間格式化的方法
這篇文章主要介紹了element-ui 表格數(shù)據(jù)時間格式化的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08electron中使用本地數(shù)據(jù)庫的方法詳解
眾所周知,electron是可以開發(fā)桌面端的框架,那我們有一些數(shù)據(jù)不想讓別人看到,只能在自己的電腦上展示時怎么辦呢,這個時候就可以用到本地數(shù)據(jù)庫,本文將以sqlite3為例介紹一下electron如何使用本地數(shù)據(jù)庫2023-10-10Vue?element-ui表格內(nèi)嵌進(jìn)度條功能實現(xiàn)方法
Element-Ul是餓了么前端團(tuán)隊推出的一款基于Vue.js 2.0 的桌面端UI框架,下面這篇文章主要給大家介紹了關(guān)于Vue?element-ui表格內(nèi)嵌進(jìn)度條功能的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-03-03