首页 > 解决方案 > 使用 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 类型

标签: javascriptphpformsapiasynchronous

解决方案


代码应该可以进行一些更改。你有两种方法(参见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)。


推荐阅读