Skip to content

Instantly share code, notes, and snippets.

@yunusemredilber
Created September 10, 2019 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yunusemredilber/9278b546c9e254d17ffc90196d2e11f7 to your computer and use it in GitHub Desktop.
Save yunusemredilber/9278b546c9e254d17ffc90196d2e11f7 to your computer and use it in GitHub Desktop.
One by one multiple file (image) upload [Ruby on Rails] [StimulusJS]
<%= form_with(model: content, id: 'content_form',
data: {controller: 'image-upload',
target: 'image-upload.form',
action: 'ajax:beforeSend->image-upload#submit'}) do |form| %>
<div data-target="image-upload.imagePreviews"></div>
<%= form.file_field :photos, multiple: true,
accept: "image/*;capture=camera|library",
data: { action: "image-upload#multiImageDisplay" } %>
<%= form.submit "Add", data: {target: "content-form.submitButton", disable_with: 'Please wait...'} %>
<% end %>
import {Controller} from "stimulus"
export default class extends Controller {
static targets = ["imagePreviews", "form"];
connect() {
console.log('image-upload_controller connected...');
}
multiImageDisplay(event) {
const files = Array.from(event.target.files); // Get files as array from FileList object
// Read files and append them to view
if (files && files[0]){
files.forEach((file) => {
const reader = new FileReader();
const readSuccess = (e) => {
const child = document.createElement("DIV");
const image_html = `<img width="75" src="${e.target.result}">`;
child.innerHTML = image_html;
this.imagePreviewsTarget.appendChild(child);
};
reader.onload = readSuccess;
reader.readAsDataURL(file);
});
}
// Keep files on 'window.uploaded_images' because file input can only keep last selected files
if (window.uploaded_images)
window.uploaded_images = [...Array.from(event.target.files),...window.uploaded_images];
else
window.uploaded_images = Array.from(event.target.files);
}
submit(e){
e.preventDefault();
const formData = new FormData(this.formTarget);
if(window.uploaded_images){
formData.delete('content[photos][]'); // Remove last state of file_input to prevent duplication
// Add files from 'window.uploaded_images' to our FormData
window.uploaded_images.map((file)=>{
formData.append('content[photos][]',file);
});
}
// Submit form with simple ajax
$.ajax({
url: 'contents',
type: 'POST',
data: formData,
contentType: false,
processData: false
});
window.uploaded_images = undefined; // Clean 'window.uploaded_images' after submit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment