I would like to send a file as payload that has been stored in a state variable and now want to set it as my payload for my API-Request.
In code below I do:
User uploads a file in the
<input type="file" name="file" onChange={changeHandler} class="custom-file-input"/>
If the user click on the button:
<Button variant="contained" onClick={handleClick}>Upload File</Button>
it triggers the API Requests. Before that it stores the file from the input inside a FormData:const formData = new FormData();
formData.append('file', selectedFile);
After that I tried to set my payload in the API Request body:
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 and purpose are necessary properties inside my api-requests.
Complete Code:
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>}
</>
)
}