我正在使用这个答案和那个答案中的代码将base64编码的图像发送到python FastAPI后端。
客户端看起来像这样:
function toDataURL(src, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function() {
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
var dataURL;
canvas.height = this.naturalHeight;
canvas.width = this.naturalWidth;
ctx.drawImage(this, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
};
img.src = src;
if (img.complete || img.complete === undefined) {
img.src = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
img.src = src;
}
}
function makeBlob(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = decodeURIComponent(parts[1]);
return new Blob([raw], { type: contentType });
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
...
toDataURL(
images[0], // images is an array of paths to images
function(dataUrl) {
console.log('RESULT:', dataUrl);
$.ajax({
url: "http://0.0.0.0:8000/check/",
type: 'POST',
processData: false,
contentType: 'application/octet-stream',
data: makeBlob(dataUrl)
}).done(function(data) {console.log("success");}).fail(function() {console.log("error");});
}
);
而服务器端如下:
@app.post("/check")
async def check(file: bytes = File(...)) -> Any:
// do something here
我只显示端点的签名,因为目前它还没有发生任何事情。
这是我调用后端时的输出,如上所示:
172.17.0.1:36464 - “选项/检查/HTTP/1.1”200
172.17.0.1:36464-“发布/检查/HTTP/1.1”307
172.17.0.1:36464 - “选项/检查 HTTP/1.1”200
172.17.0.1:36464 - “发布/检查 HTTP/1.1”422
所以,简而言之,我不断收到
422 error
代码,这意味着我发送的内容与端点期望的内容不匹配,但即使在阅读了一些内容之后,我仍然不清楚到底是什么问题。非常欢迎任何帮助!
如此答案中所述,上传的文件作为
form
数据发送。根据 FastAPI 文档:
表单中的数据通常使用“媒体类型”进行编码
当它不包含文件时。application/x-www-form-urlencoded
但是当表单包含文件时,它被编码为
。如果您使用multipart/form-data
,FastAPI 将知道它必须获取 来自身体正确部位的文件。File
无论您使用什么类型,
bytes
或UploadFile
,因为...
如果您将路径操作函数参数的类型声明为
,FastAPI将为您读取文件,您将收到 内容以字节为单位。bytes
因此,出现
422 Unprocessable entity
错误。在您的示例中,您发送二进制数据(使用 application/octet-stream
表示 content-type
),但是,您的 API 端点需要 form
数据(即 multipart/form-data
)。
不要发送 base64 编码的图像,而是按原样上传
file
,使用 HTML form
(如此处所示)或 Javascript,如下所示。正如其他人指出的那样,使用 JQuery 时,必须将 contentType 选项设置为 false。使用 Fetch API,如下所示,最好也将其保留,并强制浏览器设置它(以及强制的 多部分边界)。对于 async
在 FastAPI 后端的读/写,请查看 这个答案。
app.py:
import uvicorn
from fastapi import File, UploadFile, Request, FastAPI
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.post("/upload")
def upload(file: UploadFile = File(...)):
try:
contents = file.file.read()
with open("uploaded_" + file.filename, "wb") as f:
f.write(contents)
except Exception:
return {"message": "There was an error uploading the file"}
finally:
file.file.close()
return {"message": f"Successfuly uploaded {file.filename}"}
@app.get("/")
def main(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
模板/index.html
<script>
function uploadFile(){
var file = document.getElementById('fileInput').files[0];
if(file){
var formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
}
</script>
<input type="file" id="fileInput" name="file"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
如果您想使用
Axios
库进行上传,请查看这个答案。
如果您仍然需要上传base64编码的图像,您可以将数据作为
form
数据发送,使用application/x-www-form-urlencoded
作为content-type
;而在 API 的端点中,您可以定义一个 Form
字段来接收数据。下面是一个完整的工作示例,其中发送 Base64 编码的图像,由服务器接收、解码并保存到磁盘。对于base64编码,在客户端使用readAsDataURL方法。请注意,文件写入磁盘是使用同步写入完成的。在需要保存多个(或大)文件的场景中,最好使用async
书写,如这里所述。
app.py
from fastapi import Form, Request, FastAPI
from fastapi.templating import Jinja2Templates
import base64
app = FastAPI()
templates = Jinja2Templates(directory="templates")
@app.post("/upload")
def upload(filename: str = Form(...), filedata: str = Form(...)):
image_as_bytes = str.encode(filedata) # convert string to bytes
img_recovered = base64.b64decode(image_as_bytes) # decode base64string
with open("uploaded_" + filename, "wb") as f:
f.write(img_recovered)
return {"message": f"Successfuly uploaded {filename}"}
@app.get("/")
def main(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
模板/index.html
<script type="text/javascript">
function previewFile() {
const preview = document.querySelector('img');
const file = document.querySelector('input[type=file]').files[0];
const reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result; //show image in <img tag>
base64String = reader.result.replace("data:", "").replace(/^.+,/, "");
uploadFile(file.name, base64String)
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile(filename, filedata){
var formData = new FormData();
formData.append("filename", filename);
formData.append("filedata", filedata);
fetch('/upload', {
method: 'POST',
body: formData,
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
}
</script>
<input type="file" onchange="previewFile()"><br>
<img src="" height="200" alt="Image preview...">