well I am trying to upload image file to laravel server with react but this seems not to work. I tried it with blade template and its working. Now with react it not detecting the file, also i am using redux with axios for api call, here is my codes:
create-post action:
export function add_post(data) {
return function(dispatch) {
const formdata = new FormData();
formdata .append("file",data.file);
formdata .file = formdata;
return axios.post("/posts",data,{
headers:{
'content-type': 'multipart/form-data',
}
})
.then((res) => {
console.log(res.data);
dispatch(fetch_posts_data());
dispatch(post_notify({
message:"Post Created!",
type:"success"
}))
setTimeout(function(){
dispatch(close_notification())
},2000)
})
.catch((err)=>console.log(err));
};
}
createPost component:
import React, { useState } from 'react'
import { Formik,Field} from 'formik';
import * as Yup from 'yup';
import 'react-summernote/dist/react-summernote.css';
import {add_post} from "../store/thunks"
import {useDispatch} from "react-redux"
const FormSchema = Yup.object().shape({
title: Yup.string()
.min(2, 'Too Short!')
.required('Required'),
body: Yup.string()
.min(10, 'Too Short!')
.required('Required'),
});
const CreatePost = (props)=>{
const dispatch = useDispatch();
const [file,setfile] = useState(null)
const addimage = e=>{
setfile(e.target.files[0])
}
return(
<Formik
validationSchema={FormSchema}
initialValues={{
title: '',
body: ''
}}
onSubmit={values => {
dispatch(add_post({...values,file:file}));
props.history.push("/")
}}
render = {({ handleSubmit}) => (
<form onSubmit={handleSubmit}>
<div className="form-group mt-2">
<Field name="title" placeholder="title" type={'text'} component={customInputForm}/>
</div>
<div className="form-group">
<label htmlFor="#body">body</label>
<Field name="body" component={customTextarea}/>
</div>
<div className="form-group mt-2">
<label >Image</label>
<input type="file"
className="form-control" id='file' accept="image/*" onChange={addimage}/>
</div>
<div className="d-flex">
<button type="submit" className="btn btn-primary ml-auto">Add</button>
</div>
</form> )
}/>
)
}
export const customInputForm = ({field, form: {touched, errors}, ...props}) => (
<>
<label>{props.name}</label>
<input
className={`form-control ${!!(touched[field.name] && errors[field.name])?"is-invalid":""}`}
{...field}
{...props} />
{touched[field.name] && errors[field.name] && <div className="invalid-feedback d-block">{errors[field.name]}</div>}
</>
);
export const customTextarea = ({field, form: {touched, errors}, ...props}) => (
<>
<label>{props.name}</label>
<textarea style={{height:300}}
className={`form-control ${!!(touched[field.name] && errors[field.name])?"is-invalid":""}`}
name={props.name}
{...field}
{...props} ></textarea>
{touched[field.name] && errors[field.name] && <div className="invalid-feedback d-block">{errors[field.name]}</div>}
</>
);
and for server controller:
public function store(Request $request)
{
if($request->hasFile("file")){
$filenameWithExt = $request->file("file")->getClientOriginalName();
$filename= pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension = $request->file("file")->getClientOriginalExtension();
$fileNameToStore = $filename."_".time().".".$extension;
$path= $request->file("file")->storeAs("public/images",$fileNameToStore);
}
else{
$fileNameToStore = "no-image.svg";
$path="public/images/no-image.svg";
};
$post = new Post;
$post->title= $request->title;
$post->body= $request->body;
$post->image_name= $fileNameToStore;
$post->image_path = $path;
$post->save();
}
well the server is always setting $fileNameToStore to no-image.svg. this mean file is not detected i have tried a lot of suggested solution but nothing work. please hope you got a solution for this and thank you!