首页 > 解决方案 > 如何通过 XHR 请求将图像文件发送到 fastAPI

问题描述

不知道如何通过请求以 base64 字符串的形式发送图像以将其存储为 sqlite FastAPI 框架中的 blob 对象,并且不知道使用哪种方法,使用 formdata 或 ??? 有什么方法可以完成上述任务

var pimagefile  = document.getElementById("pImage").files[0];
var pimageblob  = new Blob([pimagefile],{type: 'image/jpg'});

function convertToBase64(){
       var pimageBase64 = // convert to base64 string
}
var toSend = {
        pimage: pimageBase64
}


var jsonString = JSON.stringify(toSend);

var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://127.0.0.1:8000/products/add/", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(jsonString);

标签: javascriptpythonimagexmlhttprequestfastapi

解决方案


您可以使用 FormData()。

var fd=new FormData();
fd.append("filename.txt",blob);
xhr.open("POST","url",true);
xhr.send(fd);

推荐阅读