【发布时间】:2022-09-23 04:45:19
【问题描述】:
我有一个具有数组输入和图像的表单,当发送没有图像的请求时,它会正确存储在数据库中,当图像输入和 \"Content-Type\": \"multipart/form -data\" 标头都添加了,它使用正确的数据发送请求,但输出数组数据无效。
代码用 Vue 3 编写,后端是 laravel api。
<script>
import axios from \"axios\";
export default {
name: \"AddPayloadModel\",
data() {
return {
drone_id: [],
drone_models: [],
image: null,
previewImage: null,
};
},
created() {
this.getDroneModels();
},
methods: {
getDroneModels() {
axios.get(\"http://127.0.0.1:8000/api/drone-models\").then((response) => {
this.drone_models = response.data;
});
},
imgUpload(e) {
this.image = e.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.image);
reader.onload = (e) => {
this.previewImage = e.target.result;
};
},
submit(e) {
const form = new FormData(e.target);
const inputs = Object.fromEntries(form.entries());
inputs.drone_id = Object.values(this.drone_id);
console.log(inputs.drone_id);
axios
.post(\"http://127.0.0.1:8000/api/payload-model/add\", inputs, {
headers: {
\"Content-Type\": \"multipart/form-data\",
},
})
.then((res) => {
if (res.data.isUnattachableDrones) {
console.log(res);
alert(res.data.unattachableDrones);
} else {
this.$router.push(\"/home\");
}
})
.catch((e) => {
console.error(e);
});
},
},
};
</script>
<template>
<main class=\"form-signin\">
<form @submit.prevent=\"submit\">
<h1 class=\"h3 mb-3 fw-normal\">Add Payload Model</h1>
<div class=\"form-floating\">
<input
class=\"form-control\"
autocomplete=\"off\"
name=\"brand_name\"
placeholder=\"Brand Name\"
/>
<label>Brand Name</label>
</div>
<div class=\"form-floating\">
<input
class=\"form-control\"
autocomplete=\"off\"
name=\"model_name\"
placeholder=\"Model name\"
/>
<label>Model Name</label>
</div>
<div class=\"form-floating\">
<input
class=\"form-control\"
autocomplete=\"off\"
name=\"type\"
placeholder=\"Type\"
/>
<label>Type</label>
</div>
<select
v-model=\"drone_id\"
multiple=\"multiple\"
name=\"drone_id\"
style=\"height: auto\"
class=\"form-select last-input\"
>
<template v-for=\"drone in drone_models\">
<option :value=\"drone.id\">
{{ drone.brand_name }}
</option>
</template>
</select>
<input
name=\"image\"
ref=\"fileInput\"
accept=\"image/*\"
type=\"file\"
@input=\"imgUpload\"
/>
<button class=\"w-100 btn btn-lg btn-form\" type=\"submit\">Submit</button>
</form>
</main>
</template>
-
你为什么不直接推送表单数据,如果表单数据包含文件,它不能被映射到 json 对象
-
那个怎么样?推什么而不是输入?
-
我认为我们可以发送表单数据本身,如果你想在其中放入一个数组:
foreach(this.drone_id as drone_id) { form.append(\"drone_id[]\", drone_id) }
标签: laravel api http-headers http-post vuejs3