Unable to send files to the server through the front end in the MERN project
P粉993712159
2023-08-14 20:52:51
<p>I've been trying to send an image file to the server from the React frontend, but the file isn't being sent: </p>
<p>This is my front-end code:</p>
<pre class="brush:php;toolbar:false;">useEffect(()=>{
const getImage=async ()=>{
if(file){
const data=new FormData();
data.append("name",file.name);
data.append("file",file);
const response=await API.uploadFile(data);
post.picture=response.data;
}
}
getImage();
},[file])</pre>
<p>file is the React state that contains the uploaded file</p>
<p>In the onClick event, I updated the file status using the setFile function: </p>
<pre class="brush:php;toolbar:false;"><label htmlFor="fileInput">
<Add fontSize="large" color="action"/>
</label>
<input
type="file"
id="fileInput"
style={{display:"none"}}
onChange={(e)=>{
setFile(e.target.files[0])
}
}
/></pre>
<p>This is my backend endpoint: </p>
<pre class="brush:php;toolbar:false;">router.post("/file/upload",upload.single("file"),uploadImage);</pre>
<p>I am using multer middleware: </p>
<pre class="brush:php;toolbar:false;">import multer from "multer";
import {GridFsStorage} from "multer-gridfs-storage";
import dotenv from "dotenv";
dotenv.config();
const username=process.env.DB_USERNAME;
const password=process.env.DB_PASSWORD;
//We will use the component GridFsStorage of multer-gridfs-storage to store images/files
const storage=new GridFsStorage({
//The URL of the database to which the file will be uploaded
url:`mongodb srv://${username}:${password}@cluster0.xki5wr4.mongodb.net/blog?
retryWrites=true&w=majority`,
options:{useNewUrlParser:true},
file:(request,file) => {
//The file types we will accept
const match=["image/png","image/jpg,image/jpeg"];
if(match.indexOf(file.memeType)===-1){
return `${Date.now()}-blog-${file.originalname}`;
}
//If the file extension matches
return {
bucketName:"photos",
filename:`${Date.now()}-blog-${file.originalname}`
}
}
})
export default multer({storage});</pre>
<p>This is the callback function</p>
<pre class="brush:php;toolbar:false;">const url="http://localhost:8000";
export const uploadImage=(request,response)=>{
if(!request.file){
return response.status(404).json({msg:"file not found"})
}
const imageUrl=`${url}/file/${request.file.filename}`;
return response.status(200).json({imageUrl});
}</pre>
<p>Since I am making API calls via axios interceptor, I also updated the header section
This is my header section: </p>
<pre class="brush:php;toolbar:false;">headers:{
"Accept": "application/json,form-data",
"Content-Type":"application/json",
// 'Content-Type': 'multipart/form-data'
// "Content-Type": "'application/x-www-form-urlencoded'"
}</pre>
<p>Whenever I try to upload a file, it throws an error, file not found</p>
<p>The request has been sent and the file name is normal, but the file has not been sent</p>
Your code has several errors. Fix these errors and maybe the problem will be solved:
replace:
replace:
Change status code:
Replace the header with: