![](/img/trans.png)
[英]laravel and react upload file return 500 Internal Server Error
[英]React upload file to laravel server error
好吧,我正在嘗試將圖像文件上傳到具有響應的laravel服務器,但這似乎不起作用。 我嘗試了刀片模板及其工作。 現在通過反應它沒有檢測到file
,我也在使用帶有axios
redux
進行api
調用,這是我的代碼:
創建后動作:
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組件:
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>}
</>
);
對於服務器控制器:
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();
}
服務器總是將$fileNameToStore
設置$fileNameToStore
no-image.svg
。 這意味着沒有檢測到文件,我嘗試了很多建議的解決方案,但沒有任何效果。 請希望對此有一個解決方案,謝謝!
嘗試這個:
const formdata = new FormData();
formdata.append("file",data.file);
return axios.post("/posts",formdata,{
headers:{
'content-type': 'multipart/form-data',
}
})
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.