【问题标题】:How to send an image file through XHR request to fastAPI如何通过 XHR 请求将图像文件发送到 fastAPI
【发布时间】:2021-01-10 19:12:54
【问题描述】:

不知道如何通过请求将图像作为 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);

【问题讨论】:

    标签: javascript python image xmlhttprequest fastapi


    【解决方案1】:

    您可以使用 FormData()。

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

    【讨论】:

    • 通过使用这种方法,我可以在提交表单中发送由输入字段收集的其他文本信息吗?.....
    • 我认为可以。例如,您有一个带有文本输入字段和文件上传的表单。使用 formdata,您可以收集所有数据并传递给请求。
    猜你喜欢
    • 2011-12-27
    • 2021-08-02
    • 2016-08-08
    • 2020-06-27
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2012-03-23
    相关资源
    最近更新 更多