1

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);
    }

2 Answers 2

3

You can use setRequestHeader method of XMLHttpRequest:

var xmlhttp = new XMLHttpRequest();

xmlhttp.setRequestHeader('Content-Type', 'video/mp4');
xmlhttp.setRequestHeader('Content-Length', '339108')
Sign up to request clarification or add additional context in comments.

1 Comment

You must call it after calling open()
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.