美文网首页
html5拖放上传文件

html5拖放上传文件

作者: 奥尼酱 | 来源:发表于2016-11-08 03:59 被阅读0次

    记录一个html5文件上传和接收的示例

    前端

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>Document</title>
      <style>
      #droptarget {
        height: 200px;
        background: lightblue;
      }
      </style>
    </head>
    <body>
      <div id="droptarget"></div>
      <script src="./app.js"></script>
    </body>
    </html>
    
    var droptarget = document.getElementById('droptarget');
    
    function handleEvent(event) {
        event.preventDefault();
        var data, xhr;
        if (event.type === 'drop') {
          files = event.dataTransfer.files;
          console.log(files);
          data = new FormData();
          for (let i = 0, len = files.length; i < len; ++i) {
            data.append("file" + i, files[i]);
          }
          xhr = new XMLHttpRequest();
          xhr.open('post', "http://localhost:10000/filetest");
          xhr.onloadend = (e) => {
            // console.log(e);
            console.log(xhr);
          }
          xhr.send(data);
        }
    }
    droptarget.addEventListener('dragover', handleEvent);
    droptarget.addEventListener('drop', handleEvent);
    

    nodejs koa后端demo

    var koa = require('koa');
    
    var app = koa();
    var parse = require('co-busboy');
    var fs = require('fs');
    app
      .use(function *(next) {
        this.res.setHeader("Access-Control-Allow-Origin", "*");
        this.res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        this.res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        yield next;
        
      })
      .use(function *(next) {
        if (this.request.is('multipart/*')) {
          var parts = parse(this);
          var part;
          while (part = yield parts) {
            part.pipe(fs.createWriteStream(part.fieldname));
          }
          this.body = 'ok';
        }
      })
      ;
    
    if (!module.parent) {
      app.listen(10000);
      console.log('listening on port 10000');
    }
    

    相关文章

      网友评论

          本文标题:html5拖放上传文件

          本文链接:https://www.haomeiwen.com/subject/sekauttx.html