docbrown/app/javascript/admin/controllers/image_upload_controller.js
rhymes e5226b9951
Upgrade Stimulus to 3.0 (#14869)
* Upgrade Stimulus to 3.0

* Remove unused variable

* Bump postcss from 8.3.8 to 8.3.9 (#14956)

Bumps [postcss](https://github.com/postcss/postcss) from 8.3.8 to 8.3.9.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.3.8...8.3.9)

---
updated-dependencies:
- dependency-name: postcss
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2021-10-05 20:00:37 +02:00

48 lines
1.3 KiB
JavaScript

import { Controller } from '@hotwired/stimulus';
export default class ImageUploadController extends Controller {
static targets = ['fileField', 'imageResult'];
static values = { url: String };
onFormSubmit(event) {
event.preventDefault();
const token = document.getElementsByName('authenticity_token')[0].value;
const image = this.fileFieldTarget.files[0];
const formData = new FormData();
formData.append('authenticity_token', token);
formData.append('image', image);
fetch(this.urlValue, {
method: 'POST',
headers: {
'X-CSRF-Token': window.csrfToken,
},
body: formData,
credentials: 'same-origin',
})
.then((response) => response.json())
.then((json) => {
if (json.error) {
throw new Error(json.error);
}
const { links } = json;
return this.onUploadSuccess(links);
});
}
onUploadSuccess(result) {
this.imageResultTarget.classList.remove('d-none');
const output = `
<div class="form-group">
<label for="output">Image URL:</label>
<textfield id="output" name="output" class="form-control" readonly>
${result}
</textfield>
</div>
<img width="300px" src=${result}>
`;
this.imageResultTarget.innerHTML = output;
}
}