【问题标题】:Image upload Reactjs with Laravel PHP使用 Laravel PHP 上传 Reactjs 的图片
【发布时间】:2021-05-09 12:59:10
【问题描述】:

我正在使用以下工具react-images-upload

import React, { useState } from "react";
import ImageUploader from "react-images-upload";

const App = () => {
  const [image, setImage] = useState();

  const handleSubmit = () => {
    console.log(image[0]);
    axios
      .post(
        "http://192.168.1.6:8001/api/upload",
        { image: image[0] },
        {
          headers: headers,
        }
      )
      .then((response) => {
        console.log(response);
      });
  };

  return (
    <div>
      <ImageUploader
        withIcon={true}
        singleImage={true}
        onChange={(p) => setImage(p.concat(p))}
        imgExtension={[".jpg", ".gif", ".png", ".jpeg"]}
        maxFileSize={4242880}
        withPreview={true}
        withIcon={true}
        className="text-center"
      />
      <button onClick={handleSubmit}>Upload</button>
    </div>
  );
};

export default App;

在php代码中:-

public function upload(Request $request)
    {
         
         return response()->json($request->all());    
    }

在 php 中,$request->all() 的值没有显示在响应请求中发送的文件:-

将带有文件/图像的请求发送到 php 后端的正确方法是什么?

【问题讨论】:

    标签: javascript php reactjs laravel-5.8


    【解决方案1】:

    使用以下命令运行:

    import React, { useState } from "react";
    import ImageUploader from "react-images-upload";
    
    const headers = {
      Accept: "application/json", "Content-Type": "multipart/form-data; boundary=---------------------------974767299852498929531610575",
    }
    const App = () => {
      const [image, setImage] = useState();
    
      const handleSubmit = () => {
        console.log(image[0]);
        axios
          .post(
            "http://192.168.1.6:8001/api/upload",
            { image: image[0] },
            {
              headers: headers,
            }
          )
          .then((response) => {
            console.log(response);
          });
      };
    
      return (
        <div>
          <ImageUploader
            withIcon={true}
            singleImage={true}
            onChange={(p) => setImage(p.concat(p))}
            imgExtension={[".jpg", ".gif", ".png", ".jpeg"]}
            maxFileSize={4242880}
            withPreview={true}
            withIcon={true}
            className="text-center"
          />
          <button onClick={handleSubmit}>Upload</button>
        </div>
      );
    };
    
    export default App;
    

    您实际上缺少标题“multipart/form-data”

    【讨论】:

    • 我试过了,api 响应中没有错误>警告:在 Unknown0
    • "Content-Type": "multipart/form-data; 边界=--------------- 974767299852498929531610575" 添加此类边界值
    • 使用 var bodyFormData = new FormData(); 解决bodyFormData.append("图像", image[0]);然后在请求 bodyFormData 中,axios 将自动检测内容类型,无需手动配置,请添加这些行来更新您的答案
    猜你喜欢
    • 2017-08-03
    • 2020-11-13
    • 2019-12-31
    • 1970-01-01
    • 2022-07-17
    • 2017-11-17
    • 1970-01-01
    • 2020-03-25
    • 2016-08-16
    相关资源
    最近更新 更多