javascript 如何将文件作为有效负载发送到Node.js中的API请求?

zkure5ic  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(132)

我想发送一个文件作为有效负载,它已经存储在一个状态变量中,现在我想将它设置为我的API请求的有效负载。
在下面的代码中我这样做:
1.用户在<input type="file" name="file" onChange={changeHandler} class="custom-file-input"/>中上传文件
1.如果用户点击按钮:<Button variant="contained" onClick={handleClick}>Upload File</Button>触发API请求。在此之前,它将来自输入的文件存储在FormData:
const formData = new FormData();
formData.append('file', selectedFile);
1.之后,我尝试在API请求主体中设置有效负载:

uploadFile(apiKey, formData);
async function uploadFile(api,payload){
(...)
                `const response = await fetch(URL,{  
                method: 'POST', 
                headers: {
                    'Authorization': `Bearer ${api}`, 
                    'Content-Type': 'multipart/form-data'
                },
                body: JSON.stringify({
                    file: payload,
                    purpose: "fine-tune"
                })
            });`
}
  • file * 和 * purpose * 是我的api请求中的必要属性。

完整代码:

function UploadFileInput(props){
    // hooks
    const [selectedFile, setSelectedFile] = useState();
    const [isSelected, setIsSelected] = useState(false);
        const apiKey = props.api;

    // upload file to OpenAI Account
     async function uploadFile(api,payload){
        const URL = "https://api.openai.com/v1/files";

        try{
            const response = await fetch(URL,{  
                method: 'POST', 
                headers: {
                    'Authorization': `Bearer ${api}`, 
                    'Content-Type': 'multipart/form-data'
                },
                body: JSON.stringify({
                    file: payload,
                    purpose: "fine-tune"
                })
            });
            //console.log("Payload: " + payload)

            // display the data in the console (if successfull)
            if(response.status === 200){
                //await response.json().then((data) =>{console.log("API RESPONSE: "+data)})
            }else{
                console.log("Error Statuscode")
            }
            

        } catch(error){
            console.log("error api fetch")
            console.error(error)
        }

    } 
        
    // upload the csv to openAI via API
    const handleClick = ()=>{

            if(!isSelected){
                console.log("no file selected.")
            }else if(isSelected){
                const formData = new FormData();
                formData.append('file', selectedFile);

                 // api call
                uploadFile(apiKey, formData);

            }else{
                console.log("Error: isSelected state doesnt exist.")
            }

            
    }

    // get the selected file from the input field and set state from "isSelected" true.
    function changeHandler(e){
        setSelectedFile(e.target.files[0]);
        setIsSelected(true);
    }

    return (
        <>
            <input type="file" name="file" onChange={changeHandler} class="custom-file-input"/>
            <Button variant="contained" onClick={handleClick}>Upload File</Button>
            {isSelected ? <p>Filename: {selectedFile.name}</p> : <p></p>}

        </>
        
    )
}
dgtucam1

dgtucam11#

我希望这个例子对你有用:

const fs = require('fs');
const request = require('request-promise')

function send() {
    const readStream = fs.createReadStream('./test.txt');
    return request({
        method: 'POST', 
        uri: 'http://localhost:8333',
        formData ={
            'file': fileStream,
        }
    });
}

async function main() {
    const response = await sendFile();
    console.log({ response });
}

main();

相关问题