首页 > 解决方案 > 尝试在更新操作上实现检索附件

问题描述

我正在关注 Andy Leverenz 的 (WebCrunch) Dropzone/Stimulus 教程,但不知道如何实现更新操作。我可以轻松上传多个文件,但是当我尝试编辑它时,我的所有附件都消失了,我必须重新上传。我认为我需要做的是在刺激控制器(@rails/ujs)上获取我的对象附件并检查浏览器 URL 是否与 edit_path 匹配,然后在加载时在表单上附加文件(document.ready)。

dropzone_controller.js

import Dropzone from "dropzone";
import { Controller } from "stimulus";
import { DirectUpload } from "@rails/activestorage";
import {
  getMetaValue,
  toArray,
  findElement,
  removeElement,
  insertAfter
} from "helpers";

export default class extends Controller {
  static targets = ["input"];

  connect() {
    this.dropZone = createDropZone(this);
    this.hideFileInput();
    this.bindEvents();
    Dropzone.autoDiscover = false;
  }

  // Private
  hideFileInput() {
    this.inputTarget.disabled = true;
    this.inputTarget.style.display = "none";
  }

  bindEvents() {
    this.dropZone.on("addedfile", file => {
      setTimeout(() => {
        file.accepted && createDirectUploadController(this, file).start();
      }, 500);
    });

    this.dropZone.on("removedfile", file => {
      file.controller && removeElement(file.controller.hiddenInput);
    });

    this.dropZone.on("canceled", file => {
      file.controller && file.controller.xhr.abort();
    });
  }

  get headers() {
    return { "X-CSRF-Token": getMetaValue("csrf-token") };
  }

  get url() {
    return this.inputTarget.getAttribute("data-direct-upload-url");
  }

  get maxFiles() {
    return this.data.get("maxFiles") || 1;
  }

  get maxFileSize() {
    return this.data.get("maxFileSize") || 256;
  }

  get acceptedFiles() {
    return this.data.get("acceptedFiles");
  }

  get addRemoveLinks() {
    return this.data.get("addRemoveLinks") || true;
  }
}

class DirectUploadController {
  constructor(source, file) {
    this.directUpload = createDirectUpload(file, source.url, this);
    this.source = source;
    this.file = file;
  }

  start() {
    this.file.controller = this;
    this.hiddenInput = this.createHiddenInput();
    this.directUpload.create((error, attributes) => {
      if (error) {
        removeElement(this.hiddenInput);
        this.emitDropzoneError(error);
      } else {
        this.hiddenInput.value = attributes.signed_id;
        this.emitDropzoneSuccess();
      }
    });
  }

  createHiddenInput() {
    const input = document.createElement("input");
    input.type = "hidden";
    input.name = this.source.inputTarget.name;
    insertAfter(input, this.source.inputTarget);
    return input;
  }

  directUploadWillStoreFileWithXHR(xhr) {
    this.bindProgressEvent(xhr);
    this.emitDropzoneUploading();
  }

  bindProgressEvent(xhr) {
    this.xhr = xhr;
    this.xhr.upload.addEventListener("progress", event =>
      this.uploadRequestDidProgress(event)
    );
  }

  uploadRequestDidProgress(event) {
    const element = this.source.element;
    const progress = (event.loaded / event.total) * 100;
    findElement(
      this.file.previewTemplate,
      ".dz-upload"
    ).style.width = `${progress}%`;
  }

  emitDropzoneUploading() {
    this.file.status = Dropzone.UPLOADING;
    this.source.dropZone.emit("processing", this.file);
  }

  emitDropzoneError(error) {
    this.file.status = Dropzone.ERROR;
    this.source.dropZone.emit("error", this.file, error);
    this.source.dropZone.emit("complete", this.file);
  }

  emitDropzoneSuccess() {
    this.file.status = Dropzone.SUCCESS;
    this.source.dropZone.emit("success", this.file);
    this.source.dropZone.emit("complete", this.file);
  }
}

function createDirectUploadController(source, file) {
  return new DirectUploadController(source, file);
}

function createDirectUpload(file, url, controller) {
  return new DirectUpload(file, url, controller);
}

function createDropZone(controller) {
  return new Dropzone(controller.element, {
    url: controller.url,
    headers: controller.headers,
    maxFiles: controller.maxFiles,
    maxFilesize: controller.maxFileSize,
    acceptedFiles: controller.acceptedFiles,
    addRemoveLinks: controller.addRemoveLinks,
    autoQueue: false
  });
}

index.js

// Load all the controllers within this directory and all subdirectories.
// Controller files must be named *_controller.js.

import { Application } from "stimulus";
import { definitionsFromContext } from "stimulus/webpack-helpers";

const application = Application.start();
const context = require.context("controllers", true, /_controller\.js$/);
application.load(definitionsFromContext(context));

_form.html.erb

<%= form_for @ad, :html => { :multipart => true } do |form| %>
  <% if ad.errors.any? %>
  <div id="error_explanation">
    <h2><%= pluralize(ad.errors.count, "error") %> prohibited this ad from being saved:</h2>

    <ul>
      <% ad.errors.each do |error| %>
      <li><%= error.full_message %></li>
      <% end %>
    </ul>
  </div>
  <% end %>

  <div class="form-group">
    <%= form.label :title %>
    <%= form.text_field :title, class: 'form-control'  %>
  </div>

  <div class="form-group">
    <%= form.label :description %>
    <%= form.text_area :description, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= form.label :images %>
    <div class='dropzone dropzone-default dz-clickable' data-controller='dropzone' data-max-filesize='2'
      data-dropzone-max-files='4'>
      <%= form.file_field :images, multiple: true, direct_upload: true, data: { target: 'dropzone.input' } %>
      <div class='dropzone-msg dz-message needsclick'>
        <h3 class='dropzone-msg-title'>Drag here to upload or click here to browse</h3>
        <span class='dropzone-msg-desc'>2 MB file size maximum. Allow file types png, jpg.</span>
      </div>
    </div>
  </div>

  <div class="form-group">
    <%= form.submit class: 'btn btn-primary mb-2' %>
  </div>
<% end %>

标签: ruby-on-railsrubydropzone.jsstimulusjs

解决方案


推荐阅读