I am attempting to upload an image to active storage in my Rails backend. I currently have the backend setup correctly but I am struggling to understand FormData. Here is what I have.
The on change function is listening for a change in the input which is of type 'file'. 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. The e.target.value here is a uri that is protected. So I'm confused about how this is supposed to work:
By the way, setFile is just setting 'file' to that 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 ActiveStorage, use their 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
}
}
Source: Active Storage - Direct Uploads
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With