Я делаю книгу рецептов и хочу, чтобы у рецептов был выбор загрузки изображений, я использую Element-UI в этом проекте, и у них есть компонент загрузки . Тем не менее, я не очень уверен, как правильно его использовать. Я основываю это на некотором коде, который я нашел, но он на самом деле не работает, $ request, который я получаю в контроллере, всегда имеет image: null
. Я использую $intertia.post
, но при необходимости могу изменить на $http.post
.
Это то, что я пытаюсь
<el-upload
class="avatar-uploader"
action="/api/vendors/fake-upload"
accept="image/*"
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="form.image" :src="form.image" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div class="buttonImage">
<el-button v-if="form.image" class="img-button mt-1" type="warning">
Change Picture
</el-button>
</div>
</el-upload>
Соответствующие данные () в моем vue <script>
loadingImage: false,
imageFile: null,
form: {
name: '',
description: '',
image: ''
},
Это методы, которые идут с <el-upload>
handleAvatarSuccess(res, file) {
this.form.image = URL.createObjectURL(file.raw);
this.loadingImage = false;
},
beforeAvatarUpload(file) {
this.imageFile = file;
const isJPG = file.type === 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isJPG) {
this.$message.error('This picture must be a JPG!');
}
if (!isLt2M) {
this.$message.error('This image is bigger than 2MB!');
}
this.loadingImage = true;
return isLt2M && isJPG;
},
Вот как я отправляю его на контроллер
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
if (!this.form.id) {
this.$inertia.post(this.baseUrl, {
name: this.form.name,
description: this.form.description,
category: this.category,
steps: this.steps,
ingredient: this.ingredient,
measurements: this.measurements,
image: this.imageFile
}).then(
() => {
this.recipe = this.$page.recipe;
this.$message({
type: 'success',
message: 'Created correctly.'
});
this.loading = false
},
(res) => {
this.$message.error(parseError(res)[0]);
this.loading = false;
})
}
} else {
return false;
}
this.reset();
});
},
Чтоправильный способ сделать это, или есть более простой способ?