Mohl
Mohl

Reputation: 415

Persist dropzone files in Session storage

I am trying to temporary persist some form data in the session storage and can't find a way to properly store enqueued (not uploaded) dropzone.js files.

Accoring to documentation, I already tried the following:

storing:

dropzone.getQueuedFiles().forEach(function(file, index) {
      sessionStorage.setItem("picture_" + index, file.dataURL);
      sessionStorage.setItem("picture_" + index + "_name", file.name);
      sessionStorage.setItem("picture_" + index + "_type", file.type);
    })

retrieving after DOM rendered:

let restoredFiles = 0;
  for(let i =0; i < dropzone.options.maxFiles; i++) {
    restoredFiles++;
    if(sessionStorage.getItem('picture_' + i) !== null){
      let data_url = sessionStorage.getItem('picture_' + i);
      let name = sessionStorage.getItem('picture_' + i + '_name');
      let type = sessionStorage.getItem('picture_' + i + '_type');
      let mockFile = {dataURL: data_url, name: name, type: type};

      dropzone.emit("addedfile", mockFile);
      dropzone.emit("thumbnail", mockFile);
      dropzone.createThumbnailFromUrl(mockFile);
      dropzone.emit("complete", mockFile);
    }
  }
dropzone.options.maxFiles = dropzone.options.maxFiles - restoredFiles;

This works fine for adding the file to Dropzone, but there is no way to show a thumbnail. Neither one of the two thumbnail commands acutally produces a thumbnail, and without an actual URL, I can't really use dropzone.createThumbnailFromUrl.

Is there a better way?

Upvotes: 1

Views: 1101

Answers (1)

Mohl
Mohl

Reputation: 415

It took a good while, but in the end, i solved it like this:

storing:

var images = [];
dropzone.getQueuedFiles().forEach(function (file) {
  let image = {
    dataURL: file.dataURL,
    name: file.name,
    type: file.type,
    size: file.size,
  };
  images.push(image);
});
sessionStorage.setItem("images", JSON.stringify(pictures));

retrieving:

var images = JSON.parse(sessionStorage.getItem('images'));
images.forEach(function(image) {
  dropzone.files.push(image);
  dropzone.emit("addedfile", image);
  dropzone.emit("thumbnail", image, image.dataURL);
  dropzone.emit("complete", image);
});
dropzone.options.maxFiles = dropzone.options.maxFiles - images.length;

Upvotes: 2

Related Questions