node+multiparty+ajax 上传图片并保存到数据库

1、html 部分

<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <title>上传图片</title>
</head>
<body>
<div class="container">
  <input  type="file" name="images" onchange="fileUpload(this)">
  <button class="btn btn-info" style="margin-top:20px" onclick="uploadPictures()">上传图片</button>
  <!--获取服务返回图片数据-->
  <div>
    <img class="img"   src="" alt="">
  </div>
</div>
<script>
  var fileImg;
  //读取图片
  function fileUpload(_this) {
    var fileReader = new FileReader();//创建文件读取对象
    fileImg = _this.files[0];//获取file组件中的文件
  }
  //上传图片
  function uploadPictures() {
    var formData = new FormData();
    formData.append("username", "zhangsan");
    //图片
    if (fileImg != null) {
      formData.append("image", fileImg);
    }
    $.ajax({
      url: 'http://127.0.0.1:8888/uploadimg',
      type: 'post',
      data: formData,
      async: true,
      processData: false,
      contentType: false,
      contextType: "application/json",
      success: function (res) {
        var res = JSON.parse(res);
        console.log(res);
        $('.img').attr('src', res.result[0].imgUrl);
      },
      error: function (err) {
        console.log(err);
      }
    });
  }
</script>
</body>
</html>

2、node部分 需要安装一下插件  

 cnpm install express mysql multiparty  --save

3、nodejs代码实现

const express = require('express');
let mysql = require("mysql");
var multiparty = require('multiparty');//获取上传的图片功能
const path = require('path');
const app = express();
let settings = require("./src/js/mySql.js");

//设置跨域访问
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
  res.header("X-Powered-By", ' 3.2.1');
  res.header("Content-Type", "text/plain");
 // res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

/********************************************上传图片*********************************************/

//注意:在客户端提交的时候
//html页面form 表单要加入 enctype="multipart/form-data"
//但是 ajax 不需要加入
//  静态文件的托管,在 upload 目录下找到图片
//  访问地址 http://127.0.0.1:8888/public/upload/images/XXXXXXXXXXX.jpg
app.use('/public/upload/images',express.static('public/upload/images'));

// 要返回的 json 数据
var myResult = {
  versionName: '4.1.6',
  versionCode: '340',
  status: '0', // 响应状态 0-成功,非0-错误码
  errorMessage: '成功',
  exception: 'xxxxxx', // 异常描述
result: [{}]
}; //获取表单提交的数据 以及post过来的图片 app.post('/uploadimg',function(req,res){ var form = new multiparty.Form(); form.uploadDir='public/upload/images'; //上传图片保存的地址(目录必须存在) form.parse(req, function(err, fields, files) {// 1、fields:获取表单的数据 2、files:图片上传成功返回的信息 myResult.result[0].code = "200"; myResult.result[0].message="success"; myResult.result[0].imgUrl='http://127.0.0.1:8888/'+files.image[0].path res.send(myResult); var url='http://127.0.0.1:8888/'+files.image[0].path; /***********************************************数据库连接**********************************************************/ let connection = mysql.createConnection(settings.db); connection.connect(); let addSql = 'INSERT INTO userImage(userId,imgUrl) VALUES(0,?)'; // connection.query(addSql,url,function (err, result) { if (err) { console.log('[INSERT ERROR] - ', err.message); return; } console.log('INSERT ID:', result); }); connection.end();//关闭数据库连接池  }); }) app.listen(8888, () => console.log('Example app listening on port 8888!'));

4、mySql.js

module.exports={
  db:{
    host: 'localhost',
    user: 'root',
    password: '******',
    port: '3306',
    database: '数据名称'
  }
};

 

posted @ 2019-04-20 10:43  (⊙o⊙)买噶  阅读(1237)  评论(0编辑  收藏  举报