ajax2.0之文件上传加跨域

express_server.js

const express=require('express');     //主体
const body=require('body-parser');    //接收普通POST数据
const multer=require('multer');       //接收文件POST数据
const mysql=require('mysql');

let db=mysql.createPool({host: 'localhost', port: 3309, user: 'root', password: '', database: '20180208'});

let server=express();
server.listen(8080);

//中间件
server.use(body.urlencoded({extended: false}));

let multerObj=multer({dest: './upload/'});
server.use(multerObj.any());

//处理请求
server.use('/api', (req, res)=>{
  if(req.headers['origin']=='null' || req.headers['origin'].startsWith('http://localhost')){
    res.setHeader('Access-Control-Allow-Origin', '*');
  }

  let arr=[];
  req.files.forEach(file=>{
    arr.push(`('${file.originalname}', '${file.filename}', ${Math.floor(Date.now()/1000)})`);
  });

  let sql=`INSERT INTO image_table (originalname, filename, time) VALUES${arr.join(',')}`;

  //console.log(sql);
  db.query(sql, (err)=>{
    if(err){
      res.send('不OK');
    }else{
      res.send("OK");
    }
  });
});

//
server.use(express.static('./www/'));

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <style media="screen">
    .parent {width:500px; height:20px; border:1px solid black;}
    .child {width:0; height:100%; background:green;}
    </style>
    <script>
    window.onload=function (){
      let oF=document.getElementById('f1');
      let oBtn=document.getElementById('btn1');

      oBtn.onclick=function (){
        let data=new FormData();

        Array.from(oF.files).forEach(file=>{
          data.append('f1', file);
        });

        //
        let oAjax=new XMLHttpRequest();

        //POST
        oAjax.open('POST', `http://localhost:8080/api`, true);

        oAjax.onprogress=function (ev){
          console.log(ev);
        };

        oAjax.upload.addEventListener('progress', function (ev){
          /*let oM=document.getElementById('m1');

          oM.value=100*ev.loaded/ev.total;*/

          let oChild=document.getElementsByClassName('child')[0];

          oChild.style.width=100*ev.loaded/ev.total+'%';
        }, false);

        oAjax.send(data);

        /*

        oAjax.onreadystatechange=function (){
          if(oAjax.readyState==4){
            if(oAjax.status>=200 && oAjax.status<300 || oAjax.status==304){
              alert('成功');
            }else{
              alert('失败');
            }
          }
        };*/
      };
    };
    </script>
  </head>
  <body>
    <div class="parent">
      <div class="child">

      </div>
    </div>
    <input type="file" id="f1" multiple /><br>
    <input type="button" value="提交" id="btn1">
  </body>
</html>

猜你喜欢

转载自www.cnblogs.com/hss-blog/p/9770475.html