通过Ajax上传文件是重复的

时间:2018-04-27 12:37:12

标签: javascript ajax

我想通过Ajax和FormData对象上传文件。为什么我的文件是重复的?



var button = document.querySelector('#send');
document.querySelector('#send').addEventListener('click', sendForm, false);
function sendForm(e) {
  e.preventDefault();
  var formElement;
  var formData;
  var xhr;
  var JSONObject;
  formElement = document.querySelector('#form');
  formData = new FormData(formElement);
  var fileInput = document.querySelector('#file');
  var files = fileInput.files;
  for (var i = 0; i < files.length; i++) {
    var file = files[i];
    formData.append('file[]', file, file.name);
  }
  console.log(...formData);
  xhr = new XMLHttpRequest();
  /**/
}
&#13;
<form id="form">
	<label for="firstname">Prénom
		<input type="text" name="firstname" id="firstname" size="30" />
	</label>
	<label for="lastname">Nom
		<input type="text" name="lastname" id="lastname" size="30" />
	</label>
	<input type="file" name="file[]" id="file" multiple>
	<button id="send" type="submit">Submit</button>
</form>
&#13;
&#13;
&#13;

我的代码出了什么问题?我的循环不正确吗?

感谢。

1 个答案:

答案 0 :(得分:1)

因为您手动将文件附加到var button = document.querySelector('#send'); document.querySelector('#send').addEventListener('click', sendForm, false); function sendForm(e) { e.preventDefault(); var formElement; var formData; var xhr; var JSONObject; formElement = document.querySelector('#form'); formData = new FormData(formElement); var fileInput = document.querySelector('#file'); /* The code that appends files in the formData, where thhey already here : var files = fileInput.files; for (var i = 0; i < files.length; i++) { var file = files[i]; formData.append('file[]', file, file.name); }*/ console.log(...formData); xhr = new XMLHttpRequest(); /**/ },因为它们已经存在。

评论不必要的代码后,您的代码运行正常。

<form id="form">
	<label for="firstname">Prénom
		<input type="text" name="firstname" id="firstname" size="30" />
	</label>
	<label for="lastname">Nom
		<input type="text" name="lastname" id="lastname" size="30" />
	</label>
	<input type="file" name="file[]" id="file" multiple>
	<button id="send" type="submit">Submit</button>
</form>
{{1}}