Express+MySQL实现图片上传到服务器并把路径保存到数据库中
demo准备:mysql5.7.20 express4.0 处理图片文件的中间件Multer
-
先搭建服务器并展示html页面
const express = require("express");
const app = express();
app.engine('html',require("html-art-template")) // 安装解析html文件的模板引擎,cnpm i html-art-template -S
app.get("/",(req,res)=>{
res.render("file.html")
})
app.listen(3001)
-
引入mysql和Multer
const mysql = require("mysql");
const multer = require("multer");
const upload = multer({dest:"uploads/"}) // 指定图片的存储位置
var connmysql = mysql.createConnection({
host:"127.0.0.1",
port:"3306",
user:"root",
password:"2232723904",
database:"picture"
})
connmysql.connect()
-
接受客户端传过来的图片文件使用post
const bodyParse = require("body-parse"); // 处理post请求的中间件
const fs = require("fs"); // 读写文件的模块
const path = require("path") // 处理路径的模块
app.use(bodyParse.urlencoded({
extended:false // 这里是返回数据为false则是对象或者数组形式,为true则为任意数据类型
}))
app.use(bodyParse.json()) // 指定post请求的数据为json数据
app.post('/picture',upload.single("imges"),(req,res)=>{
var imges = req.file;
fs.readFile(imges.path,(err,data)=>{ // 写入文件
if(err){
console.log(err,"图片读取失败")
return
}
var imgesori = imges.originalname; // 图片名称
var radname = Date.now()+parseInt(Math.random()*999)+parse(Math.random()*666) // 赋给图片的名称用时间戳+随机数获取
var oriname = imgesori.lasrIndexof(".");
var hzm = imgesori.substring(oriname,imgesori.length) // 图片后缀名
var pic = radname+pic // 拼接处一个完整的图片名称
fs.wrireFile(path.join(__dirname:'./public/image'+pic),data,(err) =>{
if(err){
console.log(err,"图片写入失败")
}
res.send({code:-1,msg:"图片上传失败"})
return
// 将图片的路径保存到数据库
var picPath = "http://localhost:3001/public/image/"+pic
var insertPic = "insert into pic_table(pic_router) values('"+picPath+"')"
connmysql.query(insertPic,(err,result)=>{
if(err){
console.log(err,"图片路径储存数据库失败")
}
res.send({code:200,msg:"图片上传成功",urls:picPath })
})
})
})
})
-
客户端页面
<body>
<div class="outbox">
<div class="skbox">
<a href="javascript:void(0)">上传<input type="file" name="pic" id="pic"
accept="image/jpeg,image/jpg,image/png,image/svg"></a>
</div>
<span></span>
<div class="imgbox"><img></div>
</div>
</body>
-
ajax部分
$(function(){
// 封装ajax函数
function update(url, formdata, callback) {
$.ajax({
url: url,
type: "POST",
data: formdata,
dataType: "json",
processData: false, // jQuery不要去处理发送的数据
contentType: false,
success: function (data) {
callback(data)
},
error: function (err) {
console.log("服务器错误!", err);
$("span").text("服务器错误,请重新上传!")
}
})
}
// 执行input时间时调用
$("input").change(function () {
var imgSize = 4000000
var zzz = /\.(jpg|png|jpeg|bmp)/i
var str = this.files[0].name
var sizes = this.files[0].size
var last = str.lastIndexOf('.')
var jq = str.substring(last, last.length).toLowerCase();
if (zzz.test(jq) && sizes <= imgSize) {
var url = "/picture"
var imgFiles = $("#pic")[0].files[0]
var formdata = new FormData()
formdata.append("imges", imgFiles)
update(url, formdata, function (data) {
console.log(data)
if (data.code < 0) {
$("span").text(data.msg)
}
$("span").text(data.msg)
var localsto = window.localStorage
localStorage.setItem("src", data.urls)
$('.imgbox img').attr('src', localsto.src);
})
} else {
alert("请选择一张正确的图片并且大小不能大于4M")
}
})
// 将服务端返回的数据保存在localStorage中
window.onload = function(){
var localsto = window.localStorage
$('.imgbox img').attr('src', localsto.src);
}
})
-
服务端完整app.js
const express = require('express')
const app = express()
const mysql = require("mysql")
const os = require("os")
const multer = require("multer")
const upload = multer({
dest: 'uploads/'
})
const bodyParser = require("body-parser")
const fs = require("fs")
const path = require("path")
var connsql = mysql.createConnection({
host: "127.0.0.1",
port: "3306",
user: "root",
password: "2232723904",
database: "picture",
})
connsql.connect()
app.engine('html', require('express-art-template'))
app.use('/public/', express.static('./public/'))
app.use(bodyParser.urlencoded({
extended: false
}))
app.use(bodyParser.json())
app.get('/', (req, res) => {
res.render('file.html')
})
app.post('/picture', upload.single('imges'), (req, res) => {
var imges = req.file
fs.readFile(imges.path, (err, data) => {
if (err) {
console.log("图片上传失败")
return;
}
var imgesori = imges.originalname
var radname = Date.now() + parseInt(Math.random() * 999)
var oriname = imgesori.lastIndexOf('.')
var hzm = imgesori.substring(oriname, oriname.length)
var pic = radname + hzm
fs.writeFile(path.join(__dirname, './public/image/' + pic), data, (err) => {
if (err) {
console.log("图片写入失败!")
res.send({
code: -1,
msg: "图片上传失败!"
})
return
}
const couter = os.networkInterfaces()
for (var cm in couter) {
var cms = couter[cm]
}
var picPath = "http://"+cms[1].address + ':3001' + '/public/image/' + pic
var insertPic = "insert into pic_table(pic_router) values('" + picPath + "')"
connsql.query(insertPic, (err, result) => {
if (err) {
console.log("保存到数据库失败!")
}
res.send({
code: 200,
msg: "图片上传成功",
urls: picPath
})
})
})
})
})
app.listen(3001)
ps:app.js中的路径时通过node中提供的os
模块获取到的
demo地址:https://github.com/dillonleader/Upload-pictures