【问题标题】:Uploading image from react to laravel api从反应上传图像到laravel api
【发布时间】:2020-09-22 13:23:51
【问题描述】:

我在将文件从 react 上传到 laravel api 时遇到问题。我有一个用于上传具有标题、正文和图像的帖子的后端。如果它们是图像,则应保存图像的 url,如果不保存默认值。我用邮递员进行了测试,它工作正常,但是当我尝试从我的反应前端上传时,它会为每次试用保存 noimage。

Laravel 接口

public function save(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'title'=>'required',
            'body'=>'required',
            'user_id'=>'required'
        ]);
        $post = new Post();
            $post->title = $request->title;
            $post->body= $request->body;
            $post->user_id= auth()->user()->id;
            if($request->hasFile('image')){
                $fileNameWithExt = $request->file('image')->getClientOriginalName();
                $fileName = pathinfo($fileNameWithExt,PATHINFO_FILENAME);
                $fileExt = $request->file('image')->getClientOriginalExtension();
                $fileNameToStore = $fileName.'_'. time() .'.'.$fileExt;
                $path = $request->file('image')->storeAs('public/images',$fileNameToStore);
            }else{
                $fileNameToStore = "NoImage.jpg";
            }
            $post->image =$fileNameToStore;
            $post->save();

        return new PostResource($post);
    }

反应代码

    const [imgName,setImgName] = useState('Choose Image');
        const [postImg,setPostImg] = useState()
        const [postData,setPostData] = useState({
            title:'',
            body:''
        });
    
        const {title,body} = postData;
    
        const changeHandler = e =>{  
           setPostData({...postData,[e.target.name]:e.target.value});
        }
    
        const fileHandler = e=>{
            setImgName(e.target.files[0].name);
            setPostImg(e.target.files[0]);
            
        }
    
        const submitHandler = e =>{
            e.preventDefault();
            
            if(!title || !body){
                props.setMsg("You can't leave title or body field blank",'warning');
                setTimeout(()=>{
                    props.clearError()
                },3000)
            }else{
                const fd = new FormData();
                fd.append('image',postImg)
                const data = {
                    title:title,
                    body:body,
                    image:fd
                }
                
                props.onCreatePost(data);
                console.log(fd.get('image'));
                
            }
           
        }

我正在使用 redux 来进行反应

`

export const createPost = (formData)=>{
    return (dispatch) =>{
        const token = localStorage.getItem('token')
        const config ={
            headers:{
                'Authorization':`Bearer ${token}`,
                
            }, 
        }
        console.log('Sent Data: ',formData);
           axios.post(`http://127.0.0.1:8000/api/posts`,formData,config)
            .then(res=>{
                dispatch(addPost(res.data))
            }).catch(err=>{
                dispatch(postfailed(err.response))
            })        
    }
}

`

【问题讨论】:

  • 请发布将图片上传到后端的代码。
  • 不清楚您的代码何时将数据发布到后端。您已声明 formdata 但似乎未使用 which ``props.onCreatePost(data);``` 将数据对象提交给定义不可用的方法
  • export const createPost = (formData)=>{ return (dispatch) =>{ const token = localStorage.getItem('token') const config ={ headers:{ 'Authorization':Bearer ${token}, }, } console.log('Sent Data: ',formData); axios.post(127.0.0.1:8000/api/posts,formData,config) .then(res=>{ dispatch(addPost(res.data)) }).catch(err=>{ dispatch(postfailed(err.response)) }) } }
  • 请将此添加到您的问题中,以使其更具可读性。
  • 我已经做到了,谢谢这是我第一次在这里提问

标签: reactjs laravel


【解决方案1】:

如果您需要在您的发布请求中包含文件,您需要以multipart/form-data 发送请求:

const config ={
    headers:{
        'Authorization':`Bearer ${token}`,
         'Content-Type': 'multipart/form-data'
     }, 
}

如果您想了解有关该主题的更多信息,我建议您阅读以下内容:application/x-www-form-urlencoded or multipart/form-data?


另外,你必须将每个字段附加为 formData,你不能创建一个带有 formdata 的 javascript 对象

代替:

const fd = new FormData();
fd.append('image',postImg)
const data = {
   title:title,
   body:body,
   image:fd
}
                
props.onCreatePost(data);

做:

const fd = new FormData();
fd.append('image',postImg)
fd.append('title', title)
fd.append('body', body)             
props.onCreatePost(fd);

【讨论】:

  • 此方法无效。我得到一个错误,我试图在数据库中插入空数据
  • 我编辑了答案,没有看到您没有使用 formData 对象
【解决方案2】:

请将您的表单数据更新为以下

const fd = new FormData();
fd.append('image',postImg)
fd.append('title', title)
fd.append('body',body)
props.onCreatePost(fd);

然后使用@gbalduzzi 解释的标题

【讨论】:

  • 哇。非常感谢你,我真的很感激
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 2018-08-30
  • 2023-03-24
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 2020-03-23
  • 2021-08-01
相关资源
最近更新 更多