简体   繁体   中英

How to add custom header in ajax request using plain javascript (NOT JQUERY)?

Please could someone advise on how to add a header to an AJAX request using plain javascript? I am trying to upload a video file to a server and want to let it know the file size and type of the file I am sending. I found someone solutions but this involved jQUERY which is not what I am after.

For example:

  Content-Length: 339108
  Content-Type: video/mp4

My AJAX request:

 var startUpload = function(){
        var formdata = new FormData();
        formdata.append('requestUpload', 'uploadTicket');

        var xmlhttp = new XMLHttpRequest;

        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var response = xmlhttp.responseText;

                if(response == '1'){

                    document.getElementById('UploadBox').innerHTML = '<div id="upWrap"><input type="file" id="vidInput"><button id="submitFile" onclick="">Upload Video<button></div>';

                }
            }
        }
        xmlhttp.open('POST', 'myFile.php');
        xmlhttp.send(formdata);
    }

You can use setRequestHeader method of XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();

xmlhttp.setRequestHeader('Content-Type', 'video/mp4');
xmlhttp.setRequestHeader('Content-Length', '339108')

You must call it after calling open() , but before calling send()

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open('GET', url, true);
xhr.setRequestHeader('accept', 'application/json, text/plain, */*');

And not all headers canbe set, refer this Forbidden_header_name

Tip: Server side should Also support Cross-Origin Resource Sharing (CORS) , like Access-Control-Allow-Origin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM