采用formdata做跨域的、无刷新、带进度条的文件上传

以前做无刷新上传,都要用iframe,如果想有进度条,就千难万难,不得不用flash等插件来实现。

现在HTML5终于普及了,筒子们不用再那么痛苦了。

所有这一切都变得异常简单!!

不信?且看如下代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>test formdata upload</title>
    <script type="text/javascript" src="jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        var onProgress = function (e) {
            if (e.lengthComputable) {
                document.getElementById("progressBar").style.width = Math.round(e.loaded * 100 / e.total) + 'px';
            }
        };
        $(function () {
            $('#uploadBtn').on('click', function () {
                var fdata = new FormData();
                fdata.append('file', $('#testFile')[0].files[0]);
                var xhr = new XMLHttpRequest();
                //xhr.onprogress = onProgress; //下载监听
                xhr.upload.onprogress = onProgress; //上传监听
                xhr.open("POST", "http://192.168.2.152:89/api/values", true);
                xhr.send(fdata);
                return false;
            });
        });
    </script>
</head>
<body>
    <div style="600px;margin:10px auto;background-color:#fff;">
        <input type="file" id="testFile" name="testFile" multiple="multiple" />
        <div id="progressBar" style="background-color:#ccf;height:8px;0px;border-radius:3px;border:0px;"></div>
        <input id="uploadBtn" type="button" value="submit" />
    </div>
</body>
</html>

webapi后台代码:

        public string Post()
        {
            if (request.Files.Count > 0)
            {
                var file = request.Files[0];
                var fileName = file.FileName.Substring(file.FileName.LastIndexOf('.'));
                file.SaveAs("D:\log\upload\" + fileName);
            }
            return "ok";
        }

注意事项:

1. webapi的webconfig添加如下内容,你懂的:

  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  <system.webServer>

2.webapi一定要发布后才能正常使用,否则chrome会报405错误,我就是在这点上被整了一整天。。。。我擦。。。。


另外,这里有一个没有解决的不算问题的问题,心有不甘,还是希望能有人帮我解决它:

就是这个代码,在chrome和firefox浏览器里执行时,会发送两个请求,第一个是个options请求,第二个才是正常的post请求,

请问有没有大侠知道如何去掉第一个options请求啊????

原文地址:https://www.cnblogs.com/foren/p/6009077.html