80 lines
2.6 KiB
JavaScript
80 lines
2.6 KiB
JavaScript
import { Controller } from '@hotwired/stimulus'
|
|
import { useFetch } from '../mixins/use_fetch'
|
|
import Dropzone from 'dropzone'
|
|
Dropzone.autoDiscover = false
|
|
|
|
/* stimulusFetch: 'lazy' */
|
|
export default class extends Controller {
|
|
|
|
static targets = ['dropzone', 'errors', 'previewTemplate']
|
|
|
|
static values = {
|
|
endpointUpload: String,
|
|
endpointDelete: String,
|
|
maxFiles: Number,
|
|
maxFilesize: Number,
|
|
acceptedFiles: String,
|
|
chunking: Boolean,
|
|
params: Object,
|
|
language: Object,
|
|
}
|
|
|
|
connect () {
|
|
useFetch(this)
|
|
|
|
this.dropzone = new Dropzone(this.dropzoneTarget, {
|
|
url: this.endpointUploadValue,
|
|
withCredentials: true,
|
|
maxFiles: this.maxFilesValue,
|
|
maxFilesize: this.maxFilesizeValue,
|
|
acceptedFiles: this.acceptedFilesValue,
|
|
chunking: true,
|
|
chunkSize: 10000000,
|
|
parallelUploads: 3,
|
|
retryChunks: true,
|
|
disablePreviews: false,
|
|
previewTemplate: this.previewTemplateTarget.innerHTML,
|
|
createImageThumbnails: true,
|
|
autoProcessQueue: true,
|
|
addRemoveLinks: false,
|
|
dictFileTooBig: this.languageValue.fileTooBig,
|
|
dictInvalidFileType: this.languageValue.invalidFileType,
|
|
dictMaxFilesExceeded: this.languageValue.maxFilesExceeded,
|
|
})
|
|
|
|
this.dropzone.on('addedfile', file => {
|
|
this.errorsTarget.classList.add('hidden')
|
|
})
|
|
|
|
this.dropzone.on('removedfile', (file) => {
|
|
fetch(`${this.endpointDeleteValue}?uuid=${file.upload.uuid}`, { method: 'delete', credentials: 'include' })
|
|
})
|
|
|
|
this.dropzone.on('sending', (file, xhr, formData) => {
|
|
if (this.hasParamsValue) {
|
|
let keys = Object.keys(this.paramsValue)
|
|
keys.forEach(key => {
|
|
formData.append(key, this.paramsValue[key])
|
|
})
|
|
}
|
|
formData.append('uuid', file.upload.uuid)
|
|
formData.append('originalFilename', file.name)
|
|
window.dispatchEvent(new CustomEvent('dropzone:uploading'))
|
|
})
|
|
|
|
this.dropzone.on('queuecomplete', () => {
|
|
window.dispatchEvent(new CustomEvent('dropzone:complete'))
|
|
})
|
|
|
|
this.dropzone.on('error', (file, errorMessage) => {
|
|
this.errorsTarget.innerText = errorMessage
|
|
this.errorsTarget.classList.remove('hidden')
|
|
dropzone.removeFile(file)
|
|
})
|
|
}
|
|
|
|
disconnect() {
|
|
this.dropzone.destroy()
|
|
}
|
|
}
|