问题
My project has React as frontend and Laravel as backend. I am trying to upload a file and the details of the file appear in state while uploading but not in the controller and hence not able to upload it in folder.
Component has
<div className="form-group col-sm-4">
<div className="imgPreview">{$imagePreview}</div>
<label>Profile Pic</label>
<input className="form-control" type="file" name="profile_pic" onChange={(e)=>this._handleImageChange(e)}/>
</div>
further codes are:
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
fileselected: file,
profile_pic: file.name,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
Data gets uploaded though axios
submitHandler = e =>{
e.preventDefault()
this.props.drprofilecreate(this.state)
}
export const drprofilecreate = (data) => dispatch =>{
console.log("Coming form profile create action ")
console.log(data)
return axios.post('/api/v1/drProfileCreate', data)
.then( res =>res.data )
.then(drprofile =>
dispatch({
type: DRPROFILECREATE,
payload: drprofile,
}),
)
}
When I view the data being uploaded, it shows the file with its details like name, size etc. But the same does not come in the controller. It shows a blank array.
public function drProfileCreate(Request $request){
$data = $request->all();
$response = [
'success' =>true,
'datax' =>'Dr Profile uploaded in Contorller. Check',
'data' => $data
];
return response()->json($response, 201);
}
Hence Iam not able to upload the image. Help please. Appreciated
回答1:
Well I think I understood what you want. Here is something that would work but I understand that other viable solutions may be there.
Basically you have to post react front end form data to back end controller using axios.
To do so you will have to handle the submit button's click event. On click of submit button the form data will be posted to desired endpoint like this:
Laravel react axios file upload
// handle button's click event
onClickHandler(){
const data = new FormData()
data.append('profile_pic', this.state.profile_pic)
axios
.post("/api/v1/drProfileCreate", data, { }) // controller will handle the upload etc
.then(response => {
console.log(response.data);
console.log(response.statusText);
})
.catch(function (error) {
console.log('Error', error.message)
})
}
// handle file change event
onChange(e){
console.log(event.target.files[0])
this.setState({
profile_pic: e.target.files[0],
})
}
// the constructor
constructor(props) {
super(props);
this.state = {
profile_pic: null,
}
}
// controller
if ($request->hasFile('profile_pic')) {
$fileName = time() . '.' . $file->getClientOriginalExtension();
// save file to storage/app/public/images directory
$file->move(storage_path('app/public/images/'), $fileName);
return response()->json('File successfully added');
}
To upload multiple files modify above code as follows:
// handle button's click event
onClickHandler(){
const data = new FormData()
//data.append('profile_pic', this.state.profile_pic)
if(this.state.profile_pic){
for(const f of this.state.profile_pic){
data.append('profile_pic[]', f)
}
}
axios
.post("/api/v1/drProfileCreate", data, { }) // controller will handle the upload etc
.then(response => {
console.log(response.data);
console.log(response.statusText);
})
.catch(function (error) {
console.log('Error', error.message)
})
}
// handle file change event
onChange(e){
//console.log(event.target.files[0])
console.log(event.target.files)
this.setState({
//profile_pic: e.target.files[0],
profile_pic: e.target.files,
})
}
// the constructor
constructor(props) {
super(props);
this.state = {
profile_pic: null,
}
}
// controller
if ($request->hasFile('profile_pic')) {
$count=0;
foreach ($request->file('profile_pic') as $file) {
$count = $count + 1;
$fileName = time() . '-'. $count .'.' . $file-
>getClientOriginalExtension();
// save file to storage/app/public/images directory
$file->move(storage_path('app/public/images/'), $fileName);
// in case you have to save all file names to database, store in an array
// $fileArray[] = $fileName;
}
return response()->json('File successfully added: '. $count);
}
来源:https://stackoverflow.com/questions/58064924/react-laravel-file-showing-in-state-but-not-in-controller