How do I show a backend image in the frontend? [duplicate]

I have created two end points in my fastapi code. One(‘/uploadlink/’) takes link as an argument and downloads the image (web scraping) and the other(‘/image_folder/image.png/’) returns the downloaded image. I have managed to download the image, but I don’t know how to display that in my frontend html.

How do I display the downloaded image?

File 1: main.py

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
import os, requests
from bs4 import BeautifulSoup
import logging
app = FastAPI()
logging.basicConfig(level=logging.INFO)
templates = Jinja2Templates(directory='templates')
app.mount("/static", StaticFiles(directory='static'), name='static')
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get('/', response_class=HTMLResponse)
async def get_basic_form(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post('/uploadlink/')
async def get_basic_form(request: Request, link: str = Form(...)):
logging.info("Method has been called")
if not os.path.exists('image_folder'):
os.makedirs('image_folder')
url = link
HEADERS = ({'User-Agent':''})
os.chdir('image_folder') # changing the directory to image_folder
webpage = requests.get(url, headers=HEADERS)
soup = BeautifulSoup(webpage.content, "html.parser")
images = soup.find_all("img", class_='hCL kVc L4E MIw')
images_list = []
real_image = ""
for img in images:
if img.has_attr('src'):
images_list.append(img['src'])
for i in range(len(images_list)):
if images_list[i].__contains__('736x'):
real_image = images_list[i]
r = requests.get(f"{real_image}") # Making the extracted binary from web as image
with open('image.png', 'wb') as f:
f.write(r.content)
return {"link": link }
@app.get("/image_folder/image.png/")
async def get_image():
return FileResponse("/image_folder/image.png")
</code>
<code>from fastapi import FastAPI, Request, Form from fastapi.responses import HTMLResponse, FileResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from fastapi.middleware.cors import CORSMiddleware import os, requests from bs4 import BeautifulSoup import logging app = FastAPI() logging.basicConfig(level=logging.INFO) templates = Jinja2Templates(directory='templates') app.mount("/static", StaticFiles(directory='static'), name='static') origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get('/', response_class=HTMLResponse) async def get_basic_form(request: Request): return templates.TemplateResponse("index.html", {"request": request}) @app.post('/uploadlink/') async def get_basic_form(request: Request, link: str = Form(...)): logging.info("Method has been called") if not os.path.exists('image_folder'): os.makedirs('image_folder') url = link HEADERS = ({'User-Agent':''}) os.chdir('image_folder') # changing the directory to image_folder webpage = requests.get(url, headers=HEADERS) soup = BeautifulSoup(webpage.content, "html.parser") images = soup.find_all("img", class_='hCL kVc L4E MIw') images_list = [] real_image = "" for img in images: if img.has_attr('src'): images_list.append(img['src']) for i in range(len(images_list)): if images_list[i].__contains__('736x'): real_image = images_list[i] r = requests.get(f"{real_image}") # Making the extracted binary from web as image with open('image.png', 'wb') as f: f.write(r.content) return {"link": link } @app.get("/image_folder/image.png/") async def get_image(): return FileResponse("/image_folder/image.png") </code>
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
import os, requests
from bs4 import BeautifulSoup
import logging

app = FastAPI()

logging.basicConfig(level=logging.INFO)

templates = Jinja2Templates(directory='templates')
app.mount("/static", StaticFiles(directory='static'), name='static')


origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get('/', response_class=HTMLResponse)
async def get_basic_form(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

@app.post('/uploadlink/')
async def get_basic_form(request: Request, link: str = Form(...)):
    logging.info("Method has been called")
    if not os.path.exists('image_folder'):
        os.makedirs('image_folder')
    
    url = link
    HEADERS = ({'User-Agent':''})
    os.chdir('image_folder')   # changing the directory to image_folder

    webpage = requests.get(url, headers=HEADERS)
    soup = BeautifulSoup(webpage.content, "html.parser")
    images = soup.find_all("img", class_='hCL kVc L4E MIw')
    images_list = []
    real_image = ""

    for img in images:
        if img.has_attr('src'):
            images_list.append(img['src'])
            
    for i in range(len(images_list)):
        if images_list[i].__contains__('736x'):
            real_image = images_list[i]
             
    r = requests.get(f"{real_image}") # Making the extracted binary from web as image
    with open('image.png', 'wb') as f:
        f.write(r.content)      
    
    return {"link": link }


@app.get("/image_folder/image.png/")
async def get_image():
    return FileResponse("/image_folder/image.png")



File 2: index.html

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<title>Pinterest</title>
</head>
<body>
<h1>Pinterest Image downloader</h1>
<form id="upload-form" enctype="multipart/form-data">
<input type="text" name="link" id="link" required>
<button type="submit" value="submit" id="downloadBtn">Download</button>
</form>
<div id="result">
<h2> Output Image: </h2><br>
<img id="generated-image" src="" alt="Generated Image" style="display: none; max-width: 100%; height: auto;">
</div>
<script>
$(document).ready(function(){
$('#upload-form').on('submit', function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: '/uploadlink/',
data: formData,
processData: false,
contentType: false,
success: function(response){
console.log(response);
$.ajax({
type: 'GET',
url: '/image_folder/image.png/',
contentType: 'application/json',
success: function(imageResponse){
console.log(imageResponse);
$('#generated-image').attr('src', '/image_folder/image.png/');
$('#generated-image').show();
}
});
}
});
});
});
</script>
</body>
</html>
</code>
<code><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <title>Pinterest</title> </head> <body> <h1>Pinterest Image downloader</h1> <form id="upload-form" enctype="multipart/form-data"> <input type="text" name="link" id="link" required> <button type="submit" value="submit" id="downloadBtn">Download</button> </form> <div id="result"> <h2> Output Image: </h2><br> <img id="generated-image" src="" alt="Generated Image" style="display: none; max-width: 100%; height: auto;"> </div> <script> $(document).ready(function(){ $('#upload-form').on('submit', function(event){ event.preventDefault(); var formData = new FormData(this); $.ajax({ type: 'POST', url: '/uploadlink/', data: formData, processData: false, contentType: false, success: function(response){ console.log(response); $.ajax({ type: 'GET', url: '/image_folder/image.png/', contentType: 'application/json', success: function(imageResponse){ console.log(imageResponse); $('#generated-image').attr('src', '/image_folder/image.png/'); $('#generated-image').show(); } }); } }); }); }); </script> </body> </html> </code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <title>Pinterest</title>
</head>
<body>
    <h1>Pinterest Image downloader</h1>
    <form id="upload-form" enctype="multipart/form-data">
        <input type="text" name="link" id="link" required>
        <button type="submit" value="submit" id="downloadBtn">Download</button>
    </form>
    <div id="result">
        <h2> Output Image: </h2><br>
        <img id="generated-image"  src="" alt="Generated Image" style="display: none; max-width: 100%; height: auto;">
    </div>
    <script>
        $(document).ready(function(){
            $('#upload-form').on('submit', function(event){
                event.preventDefault();

                var formData = new FormData(this);

                $.ajax({
                    type: 'POST',
                    url: '/uploadlink/',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response){
                        console.log(response);
                        $.ajax({
                            type: 'GET',
                            url: '/image_folder/image.png/',
                            contentType: 'application/json',
                            success: function(imageResponse){
                                console.log(imageResponse);
                                $('#generated-image').attr('src', '/image_folder/image.png/');
                                $('#generated-image').show();
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>

Error:
INFO: 127.0.0.1:60060 – “GET /image_folder/image.png/ HTTP/1.1” 500 Internal Server Error
ERROR: Exception in ASGI application
RuntimeError: File at path /image_folder/image.png does not exist

3

You always have to keep track of whether you need a URL or a filesystem path.

FileResponse in the backend expects a file name on your filesystem, not a URL. So, if you are running in the same folder that contains image_folder, just remove the first slash: FileResponse('image_folder/image.png').

However the fact that you do an os.chdir without undoing it means you have made this more complicated. If you know you’re already in image_folder, you can just FileResponse('image.png'), but I think you have made that difficult to know. What if someone does two uploads? You’ll create image_folder inside of image_folder.

Another alternative would be to make image_folder a static directory, just like you did with “static”. That way, you don’t have to handle the image URL at all.

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật