Development Tip

Ajax XmlHttpRequest로 파일 업로드

yourdevel 2021. 1. 7. 20:07
반응형

Ajax XmlHttpRequest로 파일 업로드


안녕하세요,이 코드로 xmlhttprequest로 파일을 보내려고합니다.

<script>
    var url= "http://localhost:80/....";
    $(document).ready(function(){
        document.getElementById('upload').addEventListener('change', function(e) {
            var file = this.files[0];
            var xhr = new XMLHttpRequest();
            xhr.file = file; // not necessary if you create scopes like this
            xhr.addEventListener('progress', function(e) {
                var done = e.position || e.loaded, total = e.totalSize || e.total;
                console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
            }, false);
            if ( xhr.upload ) {
                xhr.upload.onprogress = function(e) {
                    var done = e.position || e.loaded, total = e.totalSize || e.total;
                    console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
                };
            }
            xhr.onreadystatechange = function(e) {
                if ( 4 == this.readyState ) {
                    console.log(['xhr upload complete', e]);
                }
            };
            xhr.open('post', url, true);
            xhr.setRequestHeader("Content-Type","multipart/form-data");
            xhr.send(file);
        }, false);
    });
</script>

하지만이 오류가 발생했습니다. 다중 경계가 발견되지 않았기 때문에 요청이 거부되었습니다. help me pls ..


  1. 다음과 같은 것은 없습니다 xhr.file = file;. 파일 객체는 이런 식으로 첨부되지 않아야합니다.
  2. xhr.send(file)파일을 보내지 않습니다. FormData객체 를 사용하여 파일을 multipart/form-data포스트 데이터 객체 로 래핑해야 합니다.

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

그 후에 파일에 액세스 할 수 있습니다 $_FILES['thefile'](PHP를 사용하는 경우).

기억, MDC모질라 해킹 데모는 당신의 가장 친한 친구입니다.

편집 : 위의 (2)가 잘못되었습니다. 파일을 보내지 만 원시 포스트 데이터로 보냅니다. 즉, 서버에서 직접 구문 분석해야합니다 (서버 구성에 따라 가능하지 않은 경우가 많음). 여기 에서 PHP로 원시 포스트 데이터를 얻는 방법을 읽어보십시오 .

참조 URL : https://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest

반응형