[英]Upload to Rails Active Storage Using Javascript
I am attempting to upload an image to active storage in my Rails backend.我正在尝试将图像上传到我的 Rails 后端的活动存储中。 I currently have the backend setup correctly but I am struggling to understand FormData.我目前的后端设置正确,但我很难理解 FormData。 Here is what I have.这就是我所拥有的。
The on change function is listening for a change in the input which is of type 'file'.更改 function 正在侦听“文件”类型的输入中的更改。 When I add the photo to the input I can get the info from e.target... However I don't know what to add as the URI here.当我将照片添加到输入时,我可以从 e.target 获取信息......但是我不知道在此处添加什么作为 URI。 The e.target.value here is a uri that is protected.这里的 e.target.value 是一个受保护的 uri。 So I'm confused about how this is supposed to work:所以我对这应该如何工作感到困惑:
By the way, setFile is just setting 'file' to that object.顺便说一句,setFile 只是将“文件”设置为 object。 I am using react.我正在使用反应。
const onChange = (e) => {
console.log(e.target.files)
setFile({
uri: e.target.value,
name: e.target.files[0].name,
type: e.target.files[0].type
})
}
const onSubmit = () => {
console.log(file)
let imageURI = file.uri
let formdata = new FormData();
formdata.append("image", { uri: imageURI, name: `${file.name}`, type: `${file.type}` })
formdata.append("image", file)
requests.postImageToCurriculum(66, formdata)
}
if you are using Active storage, use their js package如果您使用的是活动存储,请使用他们的 js package
import { DirectUpload } from "@rails/activestorage"
class Uploader {
constructor(file, url) {
this.upload = new DirectUpload(this.file, this.url, this)
}
upload(file) {
this.upload.create((error, blob) => {
if (error) {
// Handle the error
} else {
// Add an appropriately-named hidden input to the form
// with a value of blob.signed_id
}
})
}
directUploadWillStoreFileWithXHR(request) {
request.upload.addEventListener("progress",
event => this.directUploadDidProgress(event))
}
directUploadDidProgress(event) {
// Use event.loaded and event.total to update the progress bar
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.