Gregory N. M.
Gregory N. M.

Reputation: 45

How to retrieve a URL's image from the API and display it in my view

This is not a project, I'm simply messing around with a Manga API.

I successfully retrieved the cover's URL from a book, but I'm having a hard time displaying it. The link is working, but won't display in my view. It shows only a broken image icon.

In this third party website each book has a 6 digit code as identificator, so the api gem works inputing a given code and it will retrieve the information about this specific book.

As an example I just put some random numbers and I'm trying to display this like the title and the cover.

API gem https://github.com/groussel42/nhentai-api/blob/master/lib/nhentai-api.rb

I can successfully retrieve the book's name and display it in the page title. I printed the URL's image just to show that I'm retrieving the link as well.

routes.rb:

Rails.application.routes.draw do
  get 'mangas' => 'mangas#show'
end

show.html.erb

<h1>Showing <%= @manga.title %></h1>
<%= @manga.cover%>
<%= image_tag @manga.cover %>

mangas_controller.rb

class MangasController < ApplicationController
  def show
    @manga = Doujinshi.new(250164)
  end
end

Here is my view content:

<html>
  <body>
    <h1>Showing (C94) [OrangeMaru(YD)] Yaou (Fate/Grand Order) [English] [KyuSee]</h1>
https://t.nhentai.net/galleries/1302012/cover.jpg
<img src="https://t.nhentai.net/galleries/1302012/cover.jpg">


</body></html>

Upvotes: 0

Views: 877

Answers (1)

Fernand
Fernand

Reputation: 1333

you can't display the image using the link directly because the server doesn't allow it, also known as hotlinking prevention.

you have to download the image in your backend and then display it using your own link.

controller:

require "open-uri"

File.open('public/cover.jpg', 'wb') do |fo|
  fo.write open("https://t.nhentai.net/galleries/1302012/cover.jpg").read 
end

view:

<img src="cover.jpg"/>

Upvotes: 1

Related Questions