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
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
<!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