很久沒有用Rails做web應用的前端了,當然想用最新的版本,但是好像變了很多,不知道哪個是最Rails的方式再做一次。
我嘗試使用 JQuery 和 FileUpload 插件,但我們不再有 JQuery,我的意思是我嘗試添加它,但使用新的匯入映射很麻煩(我知道我的問題如果我查找一些教程,我可以做 i),但這似乎與 Rails 應用程式中 JS 的當前心態背道而馳。
然后我去檢查了新的 Hotwire Stimulus,但我什至現在都不知道從哪里開始,但是從我看到的那一點不知道是否會處理這種情況:我已經有一個presigned_urlfrom my S3 Bucket,并且只是有一個表單f.file_field,我想直接從客戶端瀏覽器上傳這個檔案S3來做一個POST請求,所以用戶不會被阻止等待上傳完成
如果我錯了,請糾正我,但要觸發 JS 函式,Rails 方式現在可以使用Stimulus,HTML Data Attributes但我不確定我是否可以在這個資料屬性中傳遞檔案。
看著其他教程,我開始認為最好的方法是turbo_stream_tag包裝我的表單,然后在提交表單時會點擊這個 turbo 控制器,它將充當 ajax 請求,使用Net:HTTP或異步運行發布請求即使是s3寶石本身,我也不確定我是否可以訪問該檔案。
有好心人來澄清一下嗎?感謝和抱歉,很長的帖子。
uj5u.com熱心網友回復:
如果你還沒有,你可能想看看這個:https ://edgeguides.rubyonrails.org/active_storage_overview.html#example
這是一個帶有 importmaps 的默認 Rails 7 設定的啟動器。主要取自上面的示例鏈接并包含在 Stimulus 中。
# config/importmap.rb
pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true
pin "@hotwired/stimulus-loading", to: "stimulus-loading.js", preload: true
pin_all_from "app/javascript/controllers", under: "controllers"
pin "@rails/activestorage", to: "https://ga.jspm.io/npm:@rails/[email protected]/app/assets/javascripts/activestorage.esm.js"
<!-- inside your form -->
<div data-controller="upload">
<%= form.file_field :avatar, direct_upload: true,
data: { upload_target: 'input', action: "change->upload#uploadFile" } %>
<div data-upload-target="progress"></div>
</div>
這將在選擇檔案后立即開始上傳。渦輪增壓是非阻塞的。只要瀏覽器沒有重繪 ,它就會上傳。
// app/javascripts/controllers/upload_controller.js
import { Controller } from "@hotwired/stimulus";
import { DirectUpload } from "@rails/activestorage";
export default class extends Controller {
static targets = ["input", "progress"];
uploadFile() {
Array.from(this.inputTarget.files).forEach((file) => {
const upload = new DirectUpload(
file,
this.inputTarget.dataset.directUploadUrl,
this // callback directUploadWillStoreFileWithXHR(request)
);
upload.create((error, blob) => {
if (error) {
console.log(error);
} else {
this.createHiddenBlobInput(blob);
// if you're not submitting a form after upload. you need to attach
// uploaded blob to some model here and skip hidden input.
}
});
});
}
// add blob id to be submitted with the form
createHiddenBlobInput(blob) {
const hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("value", blob.signed_id);
hiddenField.name = this.inputTarget.name;
this.element.appendChild(hiddenField);
}
directUploadWillStoreFileWithXHR(request) {
request.upload.addEventListener("progress", (event) => {
this.progressUpdate(event);
});
}
progressUpdate(event) {
const progress = (event.loaded / event.total) * 100;
this.progressTarget.innerHTML = progress;
// if you navigate away from the form, progress can still be displayed
// with something like this:
// document.querySelector("#global-progress").innerHTML = progress;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452375.html
標籤:轨道上的红宝石 ruby-on-rails-7 热线导轨 刺激反射
