我不确定为什么在尝试测试endpoint是否工作时会得到null
的回报。
如果删除控制器中的dd($FilePath);
,邮递员错误返回:
完整性约束冲突:1048列“FILE_PATH”不能为空(SQL:insert into
照片(
FILE_PATH)值(?))
注意:我的Laravel代码库和React.js代码库是完全分开的。 有人知道为什么会发生这种事吗?
下面是我的前端代码:
fileSelectedHandler = event => {
this.setState({
selectedFile: event.target.files[0]
})
}
fileUploadHandler = () => {
const fd = new FormData();
fd.append('image', this.state.selectedFile, this.state.selectedFile.name);
axios.post('http://myendpoint/api/auth/wall-of-fame', fd)
.then(res => {
console.log(res);
})
}
<form action="http://myendpoint/api/auth/wall-of-fame" encType='multipart/form-data' id="login-form" className="form">
<input type="file" name="file" onChange={this.fileSelectedHandler}/>
<button onClick={this.fileUploadHandler}>Upload</button>
</form>
下面是我的php控制器:
public function store(Request $request){
$filePath = $request->input('file')->getClientOriginalName();
$data=array('file_path'=>$filePath);
// dd($filePath);
DB::table('photos')->insert($data);
echo "Record inserted successfully.<br/>";
echo '<a href = "/insert">Click Here</a> to go back.';
}
从请求中检索文件时,请使用file
方法而不是input
方法:
$filePath = $request->file('file')->getClientOriginalName();
您可以使用hasfile
方法确定请求上是否存在文件:
if ($request->hasFile('file')) {
$filePath = $request->file('file')->getClientOriginalName();
}
请参阅此处的官方文档