Node.js实现图片上传功能
2024-08-28 02:29:22
node接口实现
const express = require('express')
const mysql = require('mysql')
const cors = require('cors') // 跨域
const bodyParser = require('body-parser') // 解析参数
const app = express()
const router = express.Router()
const multer = require('multer')//用于处理 multipart/form-data 类型的表单数据
const fs = require('fs') //引入文件模块
const path = require('path')//引入路径模块
app.listen('9000',()=>console.log('服务启动'))
const option = {
host:'localhost',
user:'***',//服务器用户名
password:'***',//密码
port:'***',//端口
database:'***',//数据库
connectTimeout:5000, // 连接超时
multipleStatements:false // 是否允许一个query中包含多条sql语句
}
app.use(cors()) //解决跨域
app.use(bodyParser.json()) //json请求
app.use(bodyParser.urlencoded({extended:false})) // 表单请求
app.use('/public',express.static(path.join(__dirname,'./www')))//存放图片上传路径
const conn = mysql.createConnection(option)
//上传接口
app.all('/upload',multer().single('img'),(req,res)=>{ let {buffer,mimetype} = req.file;
let fileName = (new Date()).getTime() + parseInt(Math.random()*3435) + parseInt(Math.random()*6575);
let fileType = mimetype.split('/')[1];
let filePath = path.join(__dirname,'/www/images')
let apath = `http://服务器ip:端口/public/images/${fileName}.${fileType}` fs.writeFile(`./www/images/${fileName}.${fileType}`,buffer,(data)=>{
if(data){
res.send({err:0,msg:"上传失败"})
}else{
conn.query("INSERT INTO 表名 VALUES ('"+fileName+"','" + fileName + "." + fileType + "','" + apath + "')") //给表中存入图片信息
res.send({err:1,msg:"上传成功",imgPath:apath})//返回给前端图片路径
}
})
})
前端页面请求
html
<input type="file" id='put'>
<img src="" alt="" width="500" >
<button id="btn">上传图片</button>
javascript
var btn = document.getElementById("btn");
let url='服务器ip:端口';
btn.onclick = function(){
//通过文件域获取上传的图片信息
var a = document.getElementById("put").files[0];
var formdata = new FormData();
formdata.append('img',a);
//console.log(formdata.get('img')) $.ajax({
url:url+'/upload',
data:formdata,
type:'get',
processData: false,//必须
contentType: false,//必须
success:function(data){
console.log(data)
var imgpath = data.imgPath
$('img').attr('src',imgpath)
}
})
}
注意:
需要先在对应目录建好文件夹
最新文章
- dotnetGen 系列终于开源了
- zzy:请求静态资源和请求动态资源, src再次请求服务器资源
- 一步一步来做WebQQ机器人-(四)(获取好友列表和群列表)
- 13. (转) Android一些布局属性详解
- 7.1SportsStore:Navigation and Checkout
- DataBase 之 数据库中的系统表
- HDU 2122
- 【转】tmux入门指南
- Android中进程生命周期的优先级
- <;转>;maven发布第三方jar的一些问题
- List、Map和Set实现类
- 【百度地图API】如何给自定义覆盖物添加事件
- 设置Linux可以查看历史命令的执行时间
- Winform ListView的用法
- 【Zookeeper】源码分析之Leader选举(一)
- Exception in thread ";main"; expected &#39;<;document start>;&#39;, but found BlockMappingStart in &#39;reader&#39;, line 23, column 2: nimbus.host: ";master";
- asp.net core系列 56 IS4使用OpenID Connect添加用户认证
- MySql开启慢查询日志并使用pt-query-digest 分析
- [转]Java工程师技术栈--成神之路
- 报错:ch.qos.logback.core.joran.spi.JoranException