晚上好,
我在编写一些代码时遇到了一点问题。我刚开始学习 React,所以任何帮助都将不胜感激。
我正在尝试使用 react-dropzone 和 Laravel 作为后端编写一个小的多图像上传页面。
当我点击提交按钮时,电子邮件地址正在通过正常,但图像发生了一些事情。图像正在通过 laravel 验证正确传递,并且if( $request->hasFile('myimages') ) {
线路正确传递,但是当它到达 foreach 循环时,它什么也没找到。我不确定这是 laravel 的事情还是反应的事情,我猜我之前使用过这个 php 上传脚本的反应。
我的反应代码如下;
import React, { Component } from "react";
import Dropzone from 'react-dropzone';
import axios from 'axios';
class SendSomething extends Component {
constructor(props) {
super(props);
this.onDrop = (files) => {
this.setState({files})
};
this.state = {
files: [],
email: ''
};
}
onChangeHandler = e => {
this.setState(
{ email: e.target.value }
)
};
onClickHandler = () => {
const data = new FormData();
data.append('emailaddress', this.state.email);
this.state.files.forEach(file => {
data.append('myimages', file, file.name);
});
axios.post("/api/endpoint", data, {
})
.then(res => {
alert(res.data.message);
this.setState({
email: '',
files: []
});
})
};
render() {
const files = this.state.files.map(file => (
<li key={file.name}>
{file.name} - {file.size} bytes
</li>
));
return (
<div>
<form>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email</label>
<input type="email" name="email" value={this.state.email} onChange={this.onChangeHandler} className="form-control" id="exampleInputEmail1" placeholder="Enter email" />
</div>
<div>
<Dropzone
onDrop={this.onDrop}
accept="image/png, image/gif, image/jpeg"
minSize={0}
maxSize={5242880}
multiple
>
{({getRootProps, getInputProps}) => (
<section className="container">
<div {...getRootProps({className: 'dropzone'})}>
<input {...getInputProps()} />
<p>Click here or drop a file to upload!</p>
</div>
<aside>
<ul>{files}</ul>
</aside>
</section>
)}
</Dropzone>
</div>
<button type="button" onClick={this.onClickHandler} className="btn btn-primary">Submit</button>
</form>
</div>
);
}
}
export default SendSomething;
我的 Laravel 代码是;
public function store(Request $request)
{
request()->validate([
'emailaddress' => 'required',
'myimages' => 'required',
'myimages.*' => 'image|mimes:jpeg,jpg,gif,png'
]);
if( $request->hasFile('myimages') ) {
foreach($request->file('myimages') as $image) {
$imageName = time() . '.' . $image->getClientOriginalExtension();
$image->move(public_path('images'), $imageName);
$data[]['emailaddress'] = $request->input('emailaddress');
$data[]['imagename'] = $imageName;
}
}
$success = ImageUpload::insert($data);
return $this->sendResponse($success, 'Uploaded successfully.');
}
感谢您提前提供任何帮助。