使用ReactJs中的axios发送POST请求时,$_FILES为空

3

我有一个文件数组,想要在php中检索它们和一些其他的字符串参数。当我从React中的FormData发送文件时,在php中以json格式接收到文件:

 "{"dataForm":{"Files":[{"path":"aust.jpeg"}]},"headers":{"content-type":"multipart/form-data"}}"

出于明显的原因,我希望将它们作为$_FILES接收,这样做是否可行,并且可以在php中将其余参数作为json读取?同时,我的php.ini已完全配置允许文件上传。

以下是Reactjs代码:

import axios from 'axios';

  const sendMail = (data, uploadedFiles) => {
  const dataForm = new FormData();
  dataForm['Files'] = uploadedFiles; // Here uploadedFiles is an array of files
  console.log(dataForm['Files'])
  axios.post('http://localhost/bickdata/mail/SendMail.php', {
    dataForm,
    headers: {
      'content-type': 'multipart/form-data'
  }
  }) .then(function (response) {
    console.log(response);
  });
}

非常感谢!

不是PHP专家,但是应该是dataForm.append('Files[]', uploadedFiles)吧? - ludwiguer
你说得对,@ludwiguer。由于我正在处理一个文件数组,所以我发布了解决方案,结果发现axios.post()默认情况下将所有数据都发送为JSON格式。感谢您的帮助! - Marcel.af
4个回答

3
原来axios.post()默认发送所有数据为JSON格式,这就是为什么php无法将文件解释为文件对象的原因。我对post请求进行了一些小修改,最终成功接收到了我的文件,以下是更新后的代码:
(现在只发送一个文件数组,但我相信多个文件也是同样的过程)
  dataForm.append( 
    "potato", 
    uploadedFiles[0], 
    uploadedFiles[0].name 
  ); 

  axios({
    method: 'post',
    url: 'http://localhost/bickdata/mail/SendMail.php',
    data: dataForm,
    headers: {'Content-Type': 'multipart/form-data' }
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

非常感谢!在我的情况下,我只需要按照你的建议更改标题,然后它就起作用了。 - Xaypanya Phongsa

2
这是在React中上传多个文件的方法。
const dataForm = new FormData();
uploadedFiles.map(file => 
    dataForm.append("Files[]", file);
}

0

0
根据MDN Web Docs,FormData的编码类型设置为multipart/form-data。参考示例代码,我成功上传了一个文件:
const api = axios.create({ baseURL: '<?php $this->getUrl() ?>' })
editPost = function(e) {
    // target is the input element
    const target = typeof e === 'string' ? document.querySelector(e) : e.target;
    let form = new FormData();
    form.append(target.name, target.type == 'file' ? target.files[0] : target.value);
    form.append('sid', '<?php echo $this->getSessionId() ?>');
    api.post('/editPost', form)
        .then((response) => {
            //...
        })
        .catch(() => {
            //...
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接