【问题标题】:Unable to upload image using axios in React with PHP无法在 React with PHP 中使用 axios 上传图像
【发布时间】:2023-02-13 13:28:38
【问题描述】:

我正在研究 Reactjs 和 Php,实际上我正在尝试将图像上传到服务器,图像正在上传但是每当我尝试打开图像然后显示“我们不支持这种文件格式”时,我该如何解决这个问题?

  1. 我正在发送包含多部分表单数据的表单数据,在 php (api) 中我使用 base64 图像将图像上传到服务器
  2. 我将图像发送到 axios (api) 的方法是正确的还是 php 代码有问题

    这是我的 nextjs 代码

    const handleSubmit: FormEventHandler<HTMLFormElement> = async (e) => {
            var imagefile = document.querySelector('#file');
                  formData.append("file", imagefile.files[0]);
                  const response = await axios({
                  method: "post",
                  url: "https://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/",
                  data: formData,
                  headers: { "Content-Type": "multipart/form-data" },
                  }).then(function (response) {
                    alert('respone is '+ response.data.msg);
                     }).catch(function (error) {
                   alert('respone is '+ error);
                    console.log("failed to get recommend playlist");
                    console.log('error is '+ error.msg);
                });
     }
    

    以下是我在 Php 端的 Api 代码

     $data = json_decode(file_get_contents("php://input"), TRUE);
      $files=file_get_contents($_FILES["file"]["tmp_name"]); 
      $image = base64_decode(explode( ',', $files)[1]);
      define('UPLOAD_DIR', 'uploads/');
     $file_ext = strtolower( end(explode('.',$file_name)));
      $image_parts = explode(";base64,", $image);
      $image_type_aux = explode("image/", $image_parts[0]);
      $image_type = $image_type_aux[1];
      $image_base64 = base64_decode($image_parts[1]);
      $file = UPLOAD_DIR . uniqid() . '.'.$file_ext;
      file_put_contents($file, $image_base64);
    

【问题讨论】:

    标签: javascript php reactjs api next.js


    【解决方案1】:

    问题来自 PHP。您可以通过使用pathinfo() 获取扩展名并使用move_uploaded_file() 将上传的文件移动到服务器来简化它。

    尝试这个

    define('UPLOAD_DIR', 'uploads/');
    $file_ext  = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
    $file_name = UPLOAD_DIR . uniqid() . time() . '.' . $file_ext;
    move_uploaded_file($_FILES["file"]["tmp_name"], $file_name);
    

    【讨论】:

    • 不工作,上传图像为 0 字节(如空)
    • @Rick 你有任何错误吗?
    • 不,但正在下载 0 字节的图像
    • 尝试使用 print_r($_FILES['file']); 进行调试,让我知道你得到了什么
    猜你喜欢
    • 2022-01-18
    • 2019-04-05
    • 2019-10-24
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-01-29
    • 2020-10-22
    • 2021-08-12
    相关资源
    最近更新 更多