我正在尝试将图像上传到Rails后端的活动存储中。我目前正确设置了后端,但是我正在努力了解FormData。这就是我所拥有的。
on change函数正在侦听'file'类型的输入中的更改。当我将照片添加到输入中时,我可以从e.target获取信息。但是,我不知道要在此处添加什么作为URI。这里的e.target.value是一个受保护的uri。所以我对应该如何工作感到困惑:
顺便说一下,setFile只是将'file'设置为该对象。我正在使用反应。
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)
}
如果使用Active Storage,请使用其js包
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
}
}