1

I'm a newbie in web development, i'm doing a web projet with fastapi and javascript. For a step of this project i have to create a button to download a file (an image) which is in the server in the directory "download". I've got the error "Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"

Here it is the my project structure :

├── api
|   └──app.py
|   └── download
|        └── test.png
|
└──static
    └──js
       └──index.js

The HTML code :

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8"/>
    <link rel="stylesheet" href=" {{ url_for('static', path='css/index.css') }} "/>
    
    <title>Title</title>
  </head>

  <body>

    <div id="download_file_div">
      <input type="submit" id="download_image" value="Télécharger">
    </div>

  </body>

  <script src=" {{ url_for('static', path='js/index.js') }} "></script>
</html>

The python code (app.py) :

#-----------------------------------#
#                                   #
#              Import               #
#                                   #
# ----------------------------------#   

from fastapi import FastAPI, HTTPException, Request, File, UploadFile, Form
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse, FileResponse

import shutil
import os

#-----------------------------------#
#                                   #
#            Variables              #
#                                   #
# ----------------------------------#   

templates = Jinja2Templates(directory="api/templates")
app = FastAPI()#title=__name__,docs_url=None,redoc_url=None)
app.mount("/static", StaticFiles(directory="static"), name="static")


#-----------------------------------#
#                                   #
#              Routes               #
#                                   #
# ----------------------------------#

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

@app.get("/obfuscation")
async def obfuscation(request:Request):
    return templates.TemplateResponse("obfuscation.html", {"request": request})

@app.get("/{path:path}")
async def redirect(request: Request, path: str):
    if path == "index":
        return RedirectResponse(url="/")
    elif path == "obfuscation":
        return RedirectResponse(url="/obfuscation")
    else:
        return RedirectResponse(url="/")
    
#others routes but useless here    

@app.get("/downloadfile")
async def download_file():
    BASE_DIR = os.path.dirname((os.path.abspath(__file__)))
    DOWNLOAD_DIR = os.path.join(BASE_DIR, "download")
    SAVE_FILE_PATH = os.path.join(DOWNLOAD_DIR, "test.png")
    file_name = "newname"
    return FileResponse(path=SAVE_FILE_PATH, media_type='image/png',filename=file_name)

And the JS code :

document.getElementById("download_image").addEventListener("click", () => {
    fetch("/downloadfile", {
        method: "GET"
    })
    .then(response => {
        response.json().then(data => console.log(data))
    });
});

I know that it's not response.json() because my image is not a json (: but i don't know how to receive the image in the front. I've been on that for 2 days and tried a lot of things but nothing really working. If someone can help me. Thanks in advance

  • Related answers can be founf [here](https://stackoverflow.com/a/73414443/17865804), [here](https://stackoverflow.com/a/71195901/17865804), as well as [here](https://stackoverflow.com/a/71193588/17865804), [here](https://stackoverflow.com/a/72053557/17865804) and [here](https://stackoverflow.com/a/73843234/17865804) – Chris Mar 03 '23 at 05:58
  • You might find [this answer](https://stackoverflow.com/a/71324775/17865804) helpful as well. – Chris Mar 03 '23 at 06:16

0 Answers0