相关疑难解决方法(0)

如何在HTML中显示Base64图像?

我无法在线显示Base64图像.

有人能指出我正确的方向吗?

<!DOCTYPE html>
<html>
  <head>
    <title>Display Image</title>
  </head>
  <body>
    <img style='display:block; width:100px;height:100px;' id='base64image'                 
       src='data:image/jpeg;base64, LzlqLzRBQ...<!-- base64 data -->' />
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

html base64 inline image

506
推荐指数
12
解决办法
95万
查看次数

如何显示 API 的“内容类型:image/jpg”响应?(反应本机)

我正在发布图像,并从后端获取处理后的图像作为响应。问题出在响应部分。无论我做什么都无法显示图像。

\n

首先,邮递员工作。所以后端很好,我在邮递员中看到图像响应。无论如何,这是 FastAPI 后端的相关部分:

\n
for img in results.imgs:\n        bytes_io = io.BytesIO()\n        img_base64 = Image.fromarray(img)\n        img_base64.save(bytes_io, format="jpeg")\n    return Response(content=bytes_io.getvalue(), media_type="image/jpeg")\n
Run Code Online (Sandbox Code Playgroud)\n

我尝试过 axios 并获取两者。

\n

Axios 的响应看起来像这样,带有标题:(我得到 200)

\n
"data": "\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd",\n  "headers": Object {\n    "content-length": "86387",\n    "content-type": "image/jpeg",\n    "date": "Thu, 05 May 2022 17:45:03 GMT",\n    "server": "uvicorn",\n  },\n
Run Code Online (Sandbox Code Playgroud)\n

如您所见,数据看起来很奇怪。

\n

这是代码:

\n
axios.post("http://10.0.0.3:8000/object-to-img", body, {\n          headers: {\n            "Content-Type": "multipart/form-data",\n          },\n        })\n        .then(function (response) {\n          setImage("data:image/jpeg;base64," + response.data);\n        })\n        .catch(function (error) {\n          console.log(error);\n        });\n
Run Code Online (Sandbox Code Playgroud)\n

这就是我尝试将其形象化的方式:

\n
<Image\n        style={{\n …
Run Code Online (Sandbox Code Playgroud)

javascript react-native axios expo fastapi

6
推荐指数
1
解决办法
3764
查看次数

如何使用 ReactJS 在前端使用 Axios,在后端使用 FastAPI 下载文件?

我正在尝试创建一个docx文件并将其发送到前端客户端应用程序,以便可以将其下载到用户的本地计算机。我使用 FastAPI 作为后端。我还使用python-docx库来创建Document.

下面的代码用于创建一个docx文件并将其保存到服务器。

@app.post("/create_file")
async def create_file(data: Item):
    document = Document()
    document.add_heading("file generated", level=1)
    document.add_paragraph("test")
    document.save('generated_file.docx')
    return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)

然后使用以下代码将创建的docx文件作为 a发送FileResponse到客户端。

@app.get("/generated_file")
async def download_generated_file():
    file_path = "generated_file.docx"
    return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)
Run Code Online (Sandbox Code Playgroud)

在客户端(我正在使用 ReactJS):

@app.post("/create_file")
async def create_file(data: Item):
    document = Document()
    document.add_heading("file generated", level=1)
    document.add_paragraph("test")
    document.save('generated_file.docx')
    return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)

调用函数generated.docx时会下载文件。downloadFile但是,该docx文件始终已损坏并且无法打开。我尝试使用txt文件,效果很好。我需要使用docx文件,我该怎么办?

javascript web reactjs axios fastapi

5
推荐指数
1
解决办法
8170
查看次数

快速 API - 如何在 GET 中显示来自 POST 的图像?

我正在使用 FastAPI 创建一个应用程序,该应用程序应该生成上传图像的调整大小版本。上传应该通过 POST/images 完成,在调用路径 /images/800x400 后,它应该显示来自数据库的随机图像,大小为 800x400。我在尝试显示图像时遇到错误。

 from fastapi.responses import FileResponse
 import uuid

 app = FastAPI()

 db = []

@app.post("/images/")
async def create_upload_file(file: UploadFile = File(...)):

    contents = await file.read() 

    db.append(file)

    with open(file.filename, "wb") as f:
        f.write(contents)

    return {"filename": file.filename}

@app.get("/images/")
async def show_image():  
     return db[0]
Run Code Online (Sandbox Code Playgroud)

作为回应我得到:

{
  "filename": "70188bdc-923c-4bd3-be15-8e71966cab31.jpg",
  "content_type": "image/jpeg",
  "file": {}
}
Run Code Online (Sandbox Code Playgroud)

我想使用: return FileResponse(some_file_path) 并在文件路径中输入上面的文件名。这是正确的思维方式吗?

python fastapi

4
推荐指数
1
解决办法
2万
查看次数

使用 pdfkit 和 FastAPI 下载 PDF 文件

我将使用 FastAPI 创建一个 API HTML,使用pdfkit. 但是,它将文件保存到我的本地磁盘。当我在线提供此API后,用户如何将该PDF文件下载到他们的计算机上?

from typing import Optional
from fastapi import FastAPI
import pdfkit

app = FastAPI()
@app.post("/htmltopdf/{url}")
def convert_url(url:str):
  pdfkit.from_url(url, 'converted.pdf')
Run Code Online (Sandbox Code Playgroud)

python pdf-generation download pdfkit fastapi

3
推荐指数
1
解决办法
6604
查看次数

在 FastAPI 中渲染 NumPy 数组

我发现如何使用 FastAPI 将 numpy 数组作为图像返回?然而,我仍然在努力展示图像,它看起来只是一个白色的方块。

io.BytesIO我像这样读入一个数组:

def iterarray(array):
    output = io.BytesIO()
    np.savez(output, array)
    yield output.get_value()
Run Code Online (Sandbox Code Playgroud)

在我的端点中,我的回报是StreamingResponse(iterarray(), media_type='application/octet-stream')

当我留空media_type以推断时,会下载一个 zip 文件。

如何将数组显示为图像?

python numpy bytesio fastapi

3
推荐指数
1
解决办法
7176
查看次数

FASTAPI:无法呈现 html 页面

我正在尝试呈现显示来自网络摄像头的视频捕获的 html 页面。但面临错误:- 500 Server Error TypeError: TemplateResponse() missing 1 required positional argument: 'context'。我在 Flask 中尝试过的相同代码,在那里工作正常。

from fastapi import FastAPI
import uvicorn
from fastapi import Depends, FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import cv2

app = FastAPI(debug=True)
templates = Jinja2Templates(directory="templates")

@app.get("/")
async def index():
    return templates.TemplateResponse("index.html")


async def gen_frames(camera_id):
    cap=  cv2.VideoCapture(0)

    while True:
        # for cap in caps:
        # # Capture frame-by-frame
        success, frame = cap.read()  # read the camera frame …
Run Code Online (Sandbox Code Playgroud)

python fastapi

2
推荐指数
1
解决办法
1505
查看次数

如何使用 FastAPI/Nextjs 显示 Matplotlib 图表而不在本地保存图表?

我正在为网站使用 Nextjs 前端和 FastAPI 后端。我在前端有一个“以太坊地址”的输入表单,并使用输入的地址,我在后端生成一个 matplotlib 图表,显示“一段时间内的以太坊余额”。现在,我尝试使用 FastAPI 返回此图表,以便可以在前端显示它。我不想在本地保存图表。

这是到目前为止我的相关代码:

前端/ nexjs 文件名为“Chart.tsx”。正文中的“ethAddress”正在捕获输入表单中输入的数据。

fetch("http://localhost:8000/image", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(ethAddress),
    }).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)

生成名为 ethBalanceTracker.py 的 matplotlib 图表的后端 python 文件

#Imports
#Logic for chart here

        plt.plot(times, balances)
        buf = BytesIO()
        plt.savefig(buf, format="png")
        buf.seek(0)

        return StreamingResponse(buf, media_type="image/png")
Run Code Online (Sandbox Code Playgroud)

使用名为 api.py 的 FastAPI 的后端 python 文件

@app.get("/image")
async def get_images() -> dict:
    return {"data": images}

@app.post("/image")
async def add_image(ethAddress: dict) -> dict:

    test = EthBalanceTracker.get_transactions(ethAddress["ethAddress"])
    images.append(test)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了上面的代码和其他一些变体。我使用是StreamingResponse因为我不想在本地保存图表。我的问题是我无法显示图表localhost:8000/images并得到一个 …

python charts matplotlib next.js fastapi

2
推荐指数
1
解决办法
2431
查看次数