[英]Why do I get a null in return when trying to store file path name in database?
I'm not sure why I'm getting null
in return when trying to test if my endpoint works.我不确定为什么在尝试测试我的端点是否工作时会得到
null
作为回报。
The table name's correct but for some reason, it isn't recognizing my file.表名是正确的,但由于某种原因,它无法识别我的文件。 My table as has more than one column despite my code and was created with
php artisan
.尽管我的代码,我的表有不止一列,并且是用
php artisan
创建的。 (I'm just trying to populate filePath
column, I'll work on others later). (我只是想填充
filePath
列,稍后我会处理其他列)。 Below's an image for reference下面是一张图片供参考
If I get rid of the dd($filePath);
如果我摆脱
dd($filePath);
which's in my controller - the Postman errors returns:这是在我的 controller - Postman 错误返回:
Integrity constraint violation: 1048 Column 'file_path' cannot be null (SQL: insert into
photos (
file_path ) values (?))
Integrity constraint violation: 1048 Column 'file_path' cannot be null (SQL: insert into
照片(
file_path ) values (?))
Note: My Laravel code base and React.js code base are completely separated.注意:我的 Laravel 代码库和 React.js 代码库是完全分开的。 Anyone have an idea as to why this is happening?
任何人都知道为什么会这样?
Here's my frontend code:这是我的前端代码:
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>
Here's my php controller:这是我的 php controller:
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.';
}
When retrive a file from Request , use the file
method instead of input
method:从Request中检索文件时,使用
file
方法而不是input
方法:
$filePath = $request->file('file')->getClientOriginalName();
You may determine if a file is present on the request using the hasFile
method:您可以使用
hasFile
方法确定请求中是否存在文件:
if ($request->hasFile('file')) {
$filePath = $request->file('file')->getClientOriginalName();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.