HTML5의 File API를 사용하여 HTML5 ajax 파일 업로드를 구현하려고합니다. 이것은 this 질문에 대한 Afzaal Ahmad Zeeshan의 대답을 기반으로합니다.HTML5 + jQuery AJAX 업로드 - 서버에 파일이 없습니다.
내 주요 목표는 나중에 사용하기 위해 .xls
및 .xlsx
스프레드 시트를 업로드 할 수있게하는 것입니다.
HTML
<form class="form-uploadXLS" method="post" action="php/uploadXLS.php" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-12">
<input type="file" name="xls" class="xls" />
</div>
</div>
<input type="button" value="Upload" class="btn-uploadXLS" />
</form>
<progress></progress>
그리고 여기가 바로 위에서 언급 한 대답처럼 jQuery를 이벤트 핸들러입니다
파일 입력 onChange
이벤트 :
$('.xls').on('change', function() {
var file = this.files[0];
var fileName = file.name;
var fileType = file.type;
var fileSize = file.size;
console.log("file name: " + fileName + ", type: " + fileType + ", size: " + fileSize);
});
이 제대로 파일의 작동 이름, 유형 및 크기가 서버에 기록됩니다.
는업로드 버튼의 onClick
이벤트 :
$('.btn-uploadXLS').on('click', function (event) {
event.preventDefault();
console.log("Upload button clicked");
var formData = new FormData($('.form-uploadXLS')[0]);
$.ajax({
url: 'php/uploadXLS.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function (stuff) {
console.log("BeforeSend");
console.log(stuff);
},
success: function (data) {
console.log("Success!");
console.log(data);
},
error: function (error) {
console.log("Error!");
console.log(error);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
, 내가 여기에 파일이 서버
if(!empty($_FILES['xls'])) {
echo '<pre>',print_r($_FILES,1),'</pre>';
}
else {
die('no $_FILES variable');
}
를 전송되었는지 확인하기 위해 PHP 코드를 사용하고있어이 결과입니다 print_r :
Array
(
[xls] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] => 0
)
)
the documentation에 따르면, 예 : 4
의미 : UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
내가 뭘 잘못하고 있니?
편집 : 내가 클릭 이벤트 리스너를 해제하고 정상으로 양식을 제출하면
, 파일이 문제없이 업로드됩니다.
나는 formData
변수에 값이 없음을 알았습니다. FormData { append=append()}
예 ajax를 사용하면 파일을 직접 보낼 수 없습니다.이 링크를 클릭하여 파일 데이터를 별도의 var에 넣은 다음 http://stackoverflow.com/questions/20097081/php-ajax-file-upload-error –
@AbhikChakraborty를 추가하십시오. 그는 이미 올바르게 처리하고 있습니다. 그가 아약스를 통해 파일을 보내는 방법에는 아무런 문제가 없습니다. –
다른 파일을 사용해 보셨습니까? 다른 브라우저? 단추 클릭 처리를 사용하지 않고 대신 (디버깅을 위해) ajax없이 작동하는지 확인하기 위해 양식을 제출해야합니까? –