zoukankan      html  css  js  c++  java
  • 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 {500px; height:20px; border:1px solid black;}
        .child {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>
  • 相关阅读:
    QT QFileDialog::getOpenFileName 对文件名进行过滤
    LeetCode 17 Letter Combinations of a Phone Number
    安装terminator与配置
    导出 .bag 文件 pointcloud 话题 到 pcd文件
    Spring SpringMVC文件上传错误(二)
    Spring SpringMVC文件上传错误(一)
    Spring配置文件中的file与classpath
    常用python的标准库
    Django之天天生鲜项目
    Django之富文本编辑器
  • 原文地址:https://www.cnblogs.com/hss-blog/p/9770475.html
Copyright © 2011-2022 走看看