javascript - 使用 Javascript 从输入字段中获取图像以将其解析为 API?
问题描述
目前正在尝试使用我在 php 中创建的图像上传类,该类将图像保存到文件夹和文本文件中,但我想从我在 Javascript 中调用的 api 中保存它,而不是通过提交表单。
在这里我试图调用api
async function createTweet(e) {
const id = document.getElementById('user-id').getAttribute('data-user-id');
const tweet = e.target.parentNode.parentNode.querySelectorAll('input')[1]
.value;
const image = e.target.parentNode.parentNode.querySelectorAll('input')[0];
console.log(image);
const data = new FormData();
data.append('userId', id);
data.append('tweet', tweet);
data.append('tweet-image', image);
try {
const conn = await fetch('php/api/api-create-tweet.php', {
method: 'POST',
body: data,
});
const res = await conn.text();
getData();
// TODO show user he has created a tweet
} catch (error) {
console.log(error);
}
}
只是想知道我可以对图像做什么,以便我可以使用 $_FILES['tweet-image'] 在我的 api 中读取文件,以及是否需要对表单数据执行任何操作以使其成为 enctype 类型
解决方案
代码应该可以进行一些更改。你有两种方法(参见FormData@developer.mozilla.org):
假设您有一个简单的表格:
<!-- just an example -->
<form method="post" action="form.php" enctype="multipart/form-data">
<input type="text" name="tweet" />
<input type="file" name="image" />
<input type="submit" />
</form>
<script>
/* prevent sending the form */
var form = document.forms[0];
form.onsubmit = function(e) {
e.preventDefault();
sendForm();
}
</script>
A.<form>
直接导入FormData()
:
<script>
async function sendForm() {
// import form input here ->
const data = new FormData(form);
const conn = await fetch('form.php', {
method: 'POST',
body: data
});
const res = await conn.text();
}
</script>
B.确保您实际上将.files[0]
from附加input[type="file"]
到formData()
:
<script>
async function sendForm() {
const data = new FormData();
const tweet = form["tweet"].value;
// notice the use of .files[0] -->
const image = form["image"].files[0];
data.append("tweet", tweet);
data.append("image", image);
const conn = await fetch('form.php', {
method: 'POST',
body: data
});
const res = await conn.text();
}
</script>
然后在您的 PHP 文件中,您应该能够在此示例中同时访问$_POST["tweet"]
(text) 和$_FILES["image"]
(file)。
推荐阅读
- pixi.js - TypeError: child.transform is undefined Pixijs Webpack
- java - 在android studio中存储带有索引的数据时字符串数组出错
- spring - 如何使用基本身份验证保护 Spring Cloud Eureka 服务?
- angularjs - 设置选择的某些选项
- c# - Unity 没有找到另一个 DLL 的 DLL 依赖项(都在 Assets 文件夹中)
- javascript - 使用 lodash 将服务响应对象值转换为数组
- javascript - HeadFirst JS:代码示例中的问题
- visual-studio - 在 Visual Studio 发布任务中将字符串数组发送到 Powershell
- jobs - 为有限时间安排每小时 FW 作业 | 奥特系统
- c++ - 安装 Folly (c++ library) 通过 vcpkg 给出错误