Files
productalert/resources/js/vue/NativeImageBlock.vue
2023-07-29 02:20:51 +08:00

128 lines
3.2 KiB
Vue

<template>
<div>
<div class="card">
<div class="card-body ratio ratio-21x9 bg-dark overflow-hidden">
<div
class="d-flex justify-content-center text-center rounded-2"
:style="bgStyle"
></div>
<div
class="position-absolute w-100 h-100 d-flex justify-content-center text-center"
>
<div v-if="isUploading" class="align-self-center">
<div class="spinner-border text-light" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
<div v-else class="align-self-center">
<input
type="file"
@change="handleFileChange"
accept="image/*"
ref="fileInput"
style="display: none"
/>
<button class="btn btn-primary" @click="openFileInput">
{{ getButtonName }}
</button>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "NativeImageBlock",
props: {
apiUrl: {
type: String,
default: "https://productalert.test/api/admin/image/upload",
},
},
data: () => ({
isUploading: false,
imgSrc: null,
placeholderSrc: "https://placekitten.com/g/2100/900",
}),
computed: {
getButtonName() {
if (this.imgSrc != null && this.imgSrc?.length > 0) {
return "Change featured image";
} else {
return "Upload featured image";
}
},
getBlurPx() {
return this.imgSrc ? 0 : 12;
},
bgStyle() {
return {
backgroundImage: `url(${this.getImgSrc})`,
backgroundPosition: "center",
backgroundSize: "cover",
filter: `blur(${this.getBlurPx}px)`,
webkitFilter: `blur(${this.getBlurPx}px)`,
};
},
getImgSrc() {
if (this.imgSrc != null && this.imgSrc?.length > 0) {
return this.imgSrc;
}
return this.placeholderSrc;
},
},
methods: {
openFileInput() {
this.$refs.fileInput.click();
},
handleFileChange(event) {
const file = event.target.files[0];
if (file) {
this.uploadImage(file);
}
},
uploadImage(file) {
this.isUploading = true;
const formData = new FormData();
formData.append("file", file);
axios
.post(this.apiUrl, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((response) => {
if (
response.data.success === 1 &&
response.data.file &&
response.data.file.url
) {
this.imgSrc = response.data.file.url;
this.$emit("saved", response.data.file.url);
} else {
console.error("Image upload failed. Invalid response format.");
}
})
.catch((error) => {
console.error("Image upload failed:", error.response); // Log the full response
})
.finally(() => {
this.isUploading = false;
});
},
},
mounted() {
this.isUploading = false;
},
};
</script>
<style scoped>
/* Add your custom styles here */
</style>