I am trying send file to server with laravel api and react but the response is null this my code in frontend
let File;
const onChangeHandler = (e) => {
File = (e.target.files[0]);
}
const send = () => {
const formData = new FormData();
formData.append("media", File);
console.log(formData)
try {
PostRequest.post("/upload-post", {"media": formData}).then(r => console.log(r.data)).catch((e) => console.log(e));
} catch (error) {
console.log(error)
}
}
and my header :
headers: {
"Content-Type": "multipart/form-data",
"Accept":"application/json",
"Authorization": Token
}
and network tab img
File log File log
CodePudding user response:
can you use store file in state. if you using class component then use state
and if it is functional component then use usestate.
import React, { useState } from 'react'
const App=()=>{
const [File,setFile]=useState(null);
const onChangeHandler = (e) => {
setFile(e.target.files[0]);
}
const send = () => {
const formData = new FormData();
formData.append("media", File);
console.log(formData)
try {
PostRequest.post("/upload-post", formData).then(r => console.log(r.data)).catch((e) => console.log(e));
} catch (error) {
console.log(error)
}
}
//user code.
return(
//your code
);
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
There is another problem, {media : formdata }not need
Please convert into like this
PostRequest.post("/upload-post", formData).then(r => console.log(r.data)).catch((e) => console.log(e));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>