我不确定我是否正在使用AJAX上传文件的以下jQuery代码中正确地从表单中获取文件。
function uploadFile() {
console.log("uploading");
var form = document.getElementById('fileForm');
var fileSelect = document.getElementById('browseInput');
console.log("check1");
var file = fileSelect.files;
var formData = new FormData();
formData.append('FileInput', file, file.name);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'default/ParseExcel', true);
xhr.send(formData);
console.log("complete");
}
我收到第39行file
未定义的错误(这是上面代码中的formData.append()
行。
我不确定我是应该从form
变量还是从fileSelect
变量中抓取文件。
完整错误:
TypeError: Argument 2 of FormData.append does not implement interface Blob.
HTML code:
<form enctype="multipart/form-data"
method="POST"
id="fileForm"
onsubmit="uploadFile()"
style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<button id="submitFormButton" type="submit" style="display: none"></button>
</form>
答案 0 :(得分:1)
试试这个:
function uploadFile(e) {
e.preventDefault();
var formElement = document.getElementById('fileForm');
var formData = new FormData(formElement);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'pack.php', true);
xhr.send(formData);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="POST" id="fileForm" onsubmit="uploadFile(event)">
<input id="browseInput" type="file" name="FileInput" />
<button id="submitFormButton" type="submit">Submit</button>
</form>
&#13;
使用
var_dump($_FILES);
输出
array (size=1)
'FileInput' =>
array (size=5)
'name' => string '3400.JPG' (length=8)
'type' => string 'image/jpeg' (length=10)
'tmp_name' => string 'E:\wamp\tmp\php38E2.tmp' (length=23)
'error' => int 0
'size' => int 164319