programing

Ajax XMLHttpRequest를 사용하여 파일 업로드

elecom 2023. 3. 14. 21:25
반응형

Ajax XMLHttpRequest를 사용하여 파일 업로드

이 코드로 XMLHttpRequest 파일을 보내려고 합니다.

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

다음의 에러가 표시됩니다.t

멀티파트 경계를 찾을 수 없어 요청이 거부되었습니다.

내가 뭘 잘못하고 있지?

  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 데모와 Mozilla Hack 데모는 가장 친한 친구입니다.

편집: 위의 (2)가 올바르지 않습니다.파일을 보내긴 하지만, raw post 데이터로 보내게 됩니다.즉, 서버상에서 직접 해석할 필요가 있습니다(서버의 설정에 따라서는 불가능한 경우가 많습니다).PHP 로의 투고 데이터를 취득하는 방법은, 이쪽을 참조해 주세요.

더 자세한 답변:

let formData = new FormData();
formData.append("fileName", audioBlob);

$.ajax({
    "url": "https://myserver.com/upload",
    "method": "POST",
    "headers": {
        "API-Key": "myApiKey",
    },
    "async":        true,
    "crossDomain":  true,
    "processData":  false,
    "contentType":  false,
    "mimeType":     "multipart/form-data",
    "data":         formData
}).done(function(response){

    console.log(response);

});

언급URL : https://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest

반응형