stay hungry stay foolish

ie8-无刷新上传

ie8及以下浏览器不支持ajax来上传文件,可通过iframe来实现无刷新上传,原理参考post跨越请求

示例:

<!DOCTYPE html>
<html>
<head>
    <title>ie8-无刷新上传</title>
    <meta charset="utf-8">
    <script type="text/javascript">
        function suc(data) {
            console.log(document.myFrame.document.body.innerHTML);
        }
    </script>
</head>
<body>
    <form action="http://localhost:8080/api" target="myFrame" method="post">
        <input type="file" name="test">
        <input type="submit" value="提交" onclick="submit()">
    </form>
    <iframe name="myFrame" onload="suc()" style="display: none;"></iframe>
</body>
</html>

server.js

const express = require('express');
const fs = require('fs');
const mime = require('mime');
const path = require('path');
const app = express();

app.post('/api',function(req,res){  
    res.send(`服务器数据`);
})

app.get('/*', function(req,res){
    sendFile(req, res);
});

app.listen(8080);
console.log('listen 8080')

function sendFile(req,res){
        var realPath = __dirname+req.url;
        var exist = fs.existsSync(realPath);
        if(exist){
            var file = fs.readFileSync(realPath);
            res.writeHead(200, {
                'Content-Type': mime.getType(path.basename(realPath)),
            });
            res.end(file);
            console.log('send static file:'+realPath);
        } else {
            res.writeHead(404);
        }
}

示例代码

注意:

  • 服务器X-Frame-Options不能设置成DENY
  • 使用该方式获取子页面数据,父子页面需要在同域下