반응형
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 ..
- 다음과 같은 것은 없습니다
xhr.file = file;
. 파일 객체는 이런 식으로 첨부되지 않아야합니다. 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
반응형
'Development Tip' 카테고리의 다른 글
클래스 "B"가 아닌 클래스 "A"가있는 div를 어떻게 선택합니까? (0) | 2021.01.07 |
---|---|
교리 2 연관성을 통한 상속 매핑 (0) | 2021.01.07 |
엔터티 프레임 워크 4.1에서 데이터 페이지를 쿼리하고 총 개수를 얻는 더 나은 방법은 무엇입니까? (0) | 2021.01.07 |
SQL Server : 트리거가 활성화되었는지 비활성화되었는지 확인하십시오. (0) | 2021.01.07 |
Visual Studio 2012의 Google 테스트 (0) | 2021.01.07 |