简体   繁体   中英

how to use ActiveStorage to upload image to the backend and get the url for the image inclded in the response sent to the frontend

I am working on implementing a feature for adding products to the backend. I have successfully added the product to the backend, from the frontend, but I am having trouble sending image of the product with the product data. I am using ActiveStorage to upload the image.

what i am trying:

  • image is sent to the backend using FormData const formData = new FormData(); formData.append("product[image]", e.target.image.files[0])) const formData = new FormData(); formData.append("product[image]", e.target.image.files[0]))
  • installed ActiveStorage in the backend
  • in the backend, I used has_one_attached:image in the product model,(I want to upload multiple images, but I am not sure how to do that so I am just trying to upload one image first)
  • in the product controller, I added image to the product params

what I am stuck on:

when the image is saved to the backend, I am not sure how to get the url for the image, so that I can send it to the frontend currently when products are sent to frontend, the image is not included in the response. I am not sure how to add the image to the response.

You can use has_many_attached declaration to attach multiple images to the products:

product.rb

has_many_attached :images

Here is how you can get the displayable URL for an image attached to a product :

Rails.application.routes.url_helpers.polymorphic_url(product.images.first)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM