javascript - 为什么我不能使用 AJAX 和 formData 发送文件?
问题描述
这是我的代码,我正在尝试将文件发送到 PHP 文件,但我不能。在 JS 中,答案是input_f.files[0]是一个[object File],但是 PHP 返回Notice: Undefined index: file...,我认为 formData 不起作用。
PHP 代码
<?php
$file = $_FILES['file']['size'];
echo $file;
JS代码
var text = document.getElementById('text');
var input_f = document.getElementById('input_f');//Input file
var xmlhttp = new XMLHttpRequest();
var formData = new FormData();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
text.innerHTML = this.response;
}
};
xmlhttp.open("POST","php/convert.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
formData.append('file', input_f.files[0]);
xmlhttp.send(formData);
解决方案
尝试这个
<?php
$file = $_FILES['file']['size'];
echo $file;
JS Code
var text = document.getElementById('text');
var input_f = document.getElementById('input_f');//Input file
var xmlhttp = new XMLHttpRequest();
var formData = new FormData();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
text.innerHTML = this.response;
}
};
xmlhttp.open("POST","php/convert.php");
formData.append('file', input_f.files[0]);
xmlhttp.send(formData);
推荐阅读
- javascript - Javascript将对象列表转换为地图
- sql - 不使用 ROW_NUMBER() 或 RANK() 从每个组中获取第一条记录
- mysql - 获取 timestampdiff 在 Grails Gorm 中不起作用
- django - /blog/ 关系“blog_post”处的 ProgrammingError 不存在 LINE 1: SELECT COUNT(*) AS “__count” FROM “blog_post” WHERE “blog_po
- python - 条形文字位于绘图 matplotlib 上方
- android - 如何在撰写中使用活动作为导航器
- pandas - 过滤点云
- pine-script - 最后交易价格 - “最后价格线”作为固定变量
- javascript - 在 Django 中将数据传递给 JavaScript 的最佳实践
- python - Python 中每个即将到来的样本的时间序列分类