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)
}
})
}

 注意

  需要先在对应目录建好文件夹

最新文章

  1. dotnetGen 系列终于开源了
  2. zzy:请求静态资源和请求动态资源, src再次请求服务器资源
  3. 一步一步来做WebQQ机器人-(四)(获取好友列表和群列表)
  4. 13. (转) Android一些布局属性详解
  5. 7.1SportsStore:Navigation and Checkout
  6. DataBase 之 数据库中的系统表
  7. HDU 2122
  8. 【转】tmux入门指南
  9. Android中进程生命周期的优先级
  10. &lt;转&gt;maven发布第三方jar的一些问题
  11. List、Map和Set实现类
  12. 【百度地图API】如何给自定义覆盖物添加事件
  13. 设置Linux可以查看历史命令的执行时间
  14. Winform ListView的用法
  15. 【Zookeeper】源码分析之Leader选举(一)
  16. Exception in thread &quot;main&quot; expected &#39;&lt;document start&gt;&#39;, but found BlockMappingStart in &#39;reader&#39;, line 23, column 2: nimbus.host: &quot;master&quot;
  17. asp.net core系列 56 IS4使用OpenID Connect添加用户认证
  18. MySql开启慢查询日志并使用pt-query-digest 分析
  19. [转]Java工程师技术栈--成神之路
  20. 报错:ch.qos.logback.core.joran.spi.JoranException

热门文章

  1. 洛谷 题解 P1736 【创意吃鱼法】
  2. synchronized,ReentrantLock解决锁冲突,脏读的问题
  3. 【JS】324- JS中的内存管理(中高级前端必备)
  4. IPV6技术笔记(剖析IPv4toIPv6)
  5. JS基础-this
  6. 【IntelliJ Idea】使用学习
  7. Brett Beauregard大神的Arduino PID算法
  8. 安卓逆向基础(002)-android虚拟机
  9. 更改CSDN博客皮肤的一种简易方法
  10. 脚本批量执行Redis命令