cors跨域上传文件(原生js版本)

2018-03-20T14:09:00

转自 酱油帝君 博客

h5部分

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
<form action="">
    <div>文件选择</div>
    <input type="file" accept="image/*" capture="microphone" id="fileToUpload" onchange="fileSelected()">
    <div>
        <div id="fileName"></div>
        <div id="fileSize"></div>
        <div id="fileType"></div>
    </div>
    <div id="progressNumber"></div>
    <div><input type="button" value="上传" onclick="uploadFile()" /></div>
</form>
</body>
</html>
<script>
    function fileSelected() {
        var file = document.getElementById('fileToUpload').files[0];
        if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024)
                fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
                fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';

            document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
            document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
            document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
        }
    }

    function uploadFile() {
        var fd = new FormData();
        fd.append("avatar", document.getElementById('fileToUpload').files[0]);
        fd.append("token", "0b42bbdb-1fd1-f082-5230-f01e585cc3d2");
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", "XXXXX");
        xhr.send(fd);
    }

    function uploadProgress(evt) {
        if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
        }
        else {
            document.getElementById('progressNumber').innerHTML = 'unable to compute';
        }
    }

    function uploadComplete(evt) {
        /* This event is raised when the server send back a response */
        alert(evt.target.responseText);
    }

    function uploadFailed(evt) {
        alert("uploadFailed:" + JSON.stringify(evt));
    }

    function uploadCanceled(evt) {
        alert("uploadCanceled:" + JSON.stringify(evt));
    }
</script>

C#部分

public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection files =context.Request.Files;
            if (files != null && files.Count > 0)
            {
                string filename = files[0].FileName;
                var filesave = "E:\\file\\" + filename;
                files[0].SaveAs(filesave);
            }
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

C#配置cors允许请求头(通过webconfig配置)

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
当前页面是本站的「Baidu MIP」版。发表评论请点击:完整版 »