我想创建一个函数,通过表单将图像和文本提交到数据库,但我一直得到错误:POST http://127.0.0.1:8000/form2/submit 500(内部服务器错误)
这是我的路线:
Route::post('/form2/submit', [Form2Controller::class, 'store']);
控制器:
public function index()
{
return Form2::all();
}
public function store(Request $request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$path = $image->store('public/images');
$data['image'] = $path;
}
$response = Form2::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
表格:
<Form @submit="saveData()" enctype="multipart/form-data">
<Field name="nomor"
type="text"
class="form-control3"
v-model="form2.nomor"
placeholder=" Nomor Telfon"
:rules="isRequired"
/>
<br>
<ErrorMessage name="nomor"/>
<br>
<Field name="image"
type="file"
class="form-control3"
v-model="form2.image"
/>
</Form>
脚本:
<script>
import axios from 'axios';
import { Form, Field, ErrorMessage} from 'vee-validate';
export default {
components: {
Form,
Field,
ErrorMessage
},
data() {
return {
form2: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: '',
},
};
},
methods: {
isRequired(value){
if (value && value.trim()){
return true;
}
return 'This is required';
},
validateEmail(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
// if the field is not a valid email
const regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return 'This field must be a valid email';
}
// All is good
return true;
},
saveData(){
axios.post('/form2/submit', this.form2).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
}
}
};
</script>
我尝试在表单中添加method=“POST”,但仍然没有帮助,为什么我没有使用任何GET方法时会收到此错误?
1条答案
按热度按时间olmpazwi1#
阅读this article有关使用axios发送多部分/表单数据的信息:
尝试阻止默认行为
此外,您不能直接绑定输入文件类型:
此link可帮助您处理