You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Laravel图片上传失败:Postman可用React报422错误

React + Laravel 图片上传422错误修复方案

问题根源

422错误属于验证失败,核心问题有两点:

  1. React端未正确构造multipart/form-data格式请求,传递的是文件路径字符串而非真实File对象
  2. Laravel控制器代码存在语法拼接错误

修复步骤

1. 修正React表单代码

需使用FormData封装表单数据,获取真实的File对象,同时移除手动设置的Content-Type(axios会自动处理multipart请求的boundary):

import React from "react";
import { useRef } from "react"
import axiosClient from "../../../axios-client";

export default function FormToAddFile(){
    const fileValue=useRef();
    const nameValue=useRef();
    const descriptionValue=useRef();

    const SaveFile=(e)=>{
        e.preventDefault(); // 阻止表单默认提交刷新页面
        
        // 构造FormData对象承载表单数据
        const formData = new FormData();
        // 添加文件(fileValue.current.files[0]才是真实的File对象)
        formData.append('image', fileValue.current.files[0]);
        formData.append('name', nameValue.current.value);
        formData.append('description', descriptionValue.current.value);

        axiosClient.post("/storefile", formData)
        .then(({data})=>{
            console.log(data)
        }).catch((err)=>{
            console.log(err)
        })
    }
    return (
        <div className="w-fit mt-4">
            <form className="grid grid-cols-1 gap-4 overflow-x-hidden " >
                <input ref={nameValue} type="text" placeholder="File Name" className="py-2 pl-2 focus:outline-none text-black font-semibold"/>
               
                <textarea ref={descriptionValue} placeholder="Description" className="resize-none py-2 pl-2 focus:outline-none text-black font-semibold"></textarea>
                <label htmlFor="inputfile" className="bg-cyan-600">
                    <input ref={fileValue} id="inputfile" type="file" className="savefilelabel" />
                </label>
                {/* 设置按钮类型为button,避免触发表单默认提交 */}
                <button type="button" onClick={SaveFile} className="savefile">Save File</button>
            </form>
        </div>
    )
}

2. 修正Laravel控制器语法错误

控制器中生成文件名的代码存在引号拼接错误,修正如下:

public function store(FilesStoreRequest $request)
{
    try {
        // 修正引号拼接错误,正确拼接随机字符串与文件后缀
        $imageName = Str::random(32) . "." . $request->image->getClientOriginalExtension();
  
        // 创建File记录
        File::create([
            'name' => $request->name,
            'image' => $imageName,
            'description' => $request->description
        ]);
  
        // 保存图片到存储目录
        Storage::disk('public')->put($imageName, file_get_contents($request->image));
  
        // 返回成功响应
        return response()->json([
            'message' => "File successfully created."
        ],200);
    } catch (\Exception $e) {
        // 返回错误响应,可添加错误信息方便调试
        return response()->json([
            'message' => "Something went really wrong!",
            'error' => $e->getMessage()
        ],500);
    }
}

补充说明

  • Postman能正常运行是因为它自动正确构造了multipart/form-data请求,包含真实文件流与正确请求头
  • 确保FilesStoreRequest验证规则中,image字段规则为required|image|mimes:jpg,jpeg|max:2048(可根据需求调整大小)

内容的提问来源于stack exchange,提问作者user23531968

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 15:48:20