【发布时间】:2020-07-16 01:08:16
【问题描述】:
我需要发布正在上传文件的用户的user_id 和email。
在 Postman 中,在 body -> form-data 部分 - 我所有的 file 作为 key 和图像作为 value 并且它成功发布(文件路径、id 和电子邮件已发送到数据库)。我不确定如何以不是user_id 和email 的表单数据的方式执行此操作,因此我将其附加到表单中,但它不起作用。
但是,在浏览器中 - 我收到 500 错误,上面写着:ErrorException: Trying to get property 'id' of non-object in file
我什至尝试删除 formData.append('user_id', this.state.id); 和 formData.append('email', this.state.email);
我做错了什么?
前端代码:
constructor(props) {
super(props);
this.state = {
selectedFile: null,
user_id: null,
email: ''
};
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onChange = this.onChange.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
componentDidMount() {
this.getId();
this.getEmail();
}
getId() {
console.log("inside getId()");
let user_id = Cookies.get("id");
this.setState({user_id: user_id}, () => console.log(this.state.user_id));
}
getEmail() {
console.log("inside getEmail");
let email = Cookies.get("email");
this.setState({email: email}, () => console.log(this.state.email));
}
onFormSubmit(e) {
e.preventDefault();
this.fileUpload(this.state.selectedFile);
}
onChange(e) {
this.setState({ selectedFile: e.target.files[0] });
}
fileUpload(file) {
const formData = new FormData()
formData.append('file', file);
formData.append('user_id', this.state.user_id);
formData.append('email', this.state.email);
fetch('http://myendpoint/api/auth/wall-of-fame', {
method: 'POST',
body: formData
})
.then(response => console.log(response))
.catch(error => { console.error(error) });
}
render() {
return (
<form encType='multipart/form-data' id="login-form" className="form" onSubmit={this.onFormSubmit}>
<input type="file" name="file" onChange={this.onChange}/>
<button type="submit">Upload</button>
</form>
);
}
后端控制器代码:
public function store(Request $request){
$filePath = $request->file('file')->getClientOriginalName();
$id = $request->user()->id;
$email = $request->user()->email;
// dd($id, $email);
$data= [
'file_path' => $filePath,
'user_id' => $id,
'email' => $email
];
DB::table('my.db')->insert($data);
echo "Record inserted successfully.<br/>";
}
【问题讨论】:
标签: javascript php reactjs laravel debugging