4

我在使用 laravel API 从反应输入上传文件时遇到问题。我正在使用 react-hook-form。我的表格和onSave如下


const onSave = data => {
        // data.picture = imgs; here I tried changing the picture to event.target.files from the file input, didn't work either.
        axios.defaults.headers.common["Authorization"] = "Bearer " + token;
        axios
            .post(`/api/products/store`, data, {})
            .then(res => {
                console.log(res);
            })
            .catch(err => console.log(err));
    };

return (
<form onSubmit={handleSubmit(onSave)} encType="multipart/form-data">
    <input
        type="file"
        name="picture[]"
        label="Product Picture"
        onChange={handlePicInput}
        className={classes.inputFile}
        multiple
        />
//other inputs
</form>
);

我的帖子请求导致此控制器方法

 public function store(Request $request)
    {
        $imageNames = '';
        $pictures = (object) $request->file('picture');
        //$pictures = $request->allFiles();
        //$pictures = (object) $request->file('picture[]');
        //$pictures = (object) $request->files;
        foreach ($pictures as  $key => $picture) {
            /*WHEN I'M USING POSTMAN OR INSOMNIA, 
             this foreach loop is accessed but 
             the react form just skips the foreach completely */
            $imageNames = $imageNames . $picture->store('product_pictures', 'public') . ',';
        }

        $product = Product::create([
            'name' => $request->name,
            'prices_amountmax' => $request->prices_amountmax,
            'prices_amountmin' => $request->prices_amountmax,
            'brand' => $request->brand,
            'manufacturer' => $request->manufacturer,
            'weight' => $request->weight,
            'category_id' => $request->category_id,
            'stock' => $request->stock,
            'imageurls' => $imageNames
        ]);
        $product->save();
    }

总结一下,我用postman测试过上传图片,效果很好,所以问题一定出在react表单上?感谢您的任何帮助

4

2 回答 2

6

要使用 js 上传图片,您可以使用 FormData。我看不到您的 handlePicInput 方法来了解如何处理输入更改,但可能这个片段可以帮助您了解进一步的操作。

function handlePicInput(event){
    let images = event.target.files
    let fd = new FormData()
    fd.append("images", images);
}

然后您可以附加到 fd 您的其他值并通过 axios 发送

axios.post(`/api/products/store`, fd)

同样,在哪里放置代码以及如何处理您必须自己管理的其他输入,或提供更多数据

于 2020-02-23T23:04:44.413 回答
4

尝试将其作为 formData 发送,包含多个文件:

const onSave = data => {

  const formData = new FormData();
    for (let i in data) {
      if(i === 'picture[]'){
        for(let file of data[i]){
            formData.append('picture',file);
        }

      }else{
        formData.append(i, data[i])
      }  

    }
  // data.picture = imgs; here I tried changing the picture to event.target.files from the file input, didn't work either.
  axios.defaults.headers.common["Authorization"] = "Bearer " + token;
  axios
      .post(`/api/products/store`, formData, {})
      .then(res => {
          console.log(res);
      })
      .catch(err => console.log(err));
}; 

我用我的 Node/Express 后端对其进行了测试,它似乎可以工作。“图片”将是一个文件数组。如果您的 php 后端无法正确识别,请尝试将 formData.append('picture',file) 更改为 formData.append('picture[]',file),但您还需要更改名称你的 php.ini

于 2020-02-23T23:16:04.920 回答