javascript 上传图像时React和多路复用不工作,图像未上传到文件夹

flvtvl50  于 2023-02-07  发布在  Java
关注(0)|答案(1)|浏览(109)

我尝试上传一个图像到一个节点服务器与multer。我已经调用了API从前端,也做了multer配置在服务器端,但一些如何,代码不工作。图像应该是上传到图像文件夹中的图像没有被上传。有人可以帮助这里吗?
下面是我的React代码:

import React, {useEffect, useState, useRef} from 'react';
import { Router, useNavigate } from 'react-router-dom';
import axios from "axios";

const Dashboard = ()=>{

const [userName, userNameSetter] = useState("");
const [userEmail, userEmailSetter] = useState("");

const [artTitle, setArtTitle] = useState("");
const [artContent, setArtContent] = useState("");

const [imagePreview, setPreview] = useState(undefined);
const [imageToSend, setImageToSend] = useState(undefined);


const fileUploadRef = useRef(null);

async function makePost(e){
//This function calls the api at that address.
    e.preventdefault();
    console.log("You have called the upload function");
    const fd = new FormData();

    fd.append("form-image", imageToSend);
    const response = await axios.post("http://localhost:1337/api/multer-photo-upload", {fd});
    console.log(response);
}



const addPostImage =()=>{
    fileUploadRef.current.click();
}



async function uploadPostImage(e){
//This function simply tests to see if the user has clicked on an image and to upload set it on the state variable. For it to be displayed
    if(e.target.files.length === 0){
        console.log("Please choose an image");
    }else{
        const imageMain = URL.createObjectURL(e.target.files[0]);
        setPreview(imageMain);

        setImageToSend(imageMain);
    }

   
}

async function performUpload(fd){

    
}
useEffect(()=>{
    let emailAdd = localStorage.getItem("email");
    let uName = localStorage.getItem("name");

    userNameSetter(uName);
    userEmailSetter(emailAdd);
});

return (
<> 
<Header />
<section className = 'dashboard-wrapper'>
<section className = 'dashboard-left'>
    <center><h1>CW ADMIN DASHBOARD</h1></center>
    <center>   
    <span className = 'u-av'>
        <i class="ri-user-fill"></i>
        </span>
        <h3>
        Welcome {userName}. <br />Your Email is {userEmail}
        </h3>
        
    </center>

</section>

<section className= 'dashboard-right'>
    <h3>UPLOAD AN ARTICLE</h3>
    <form action = '' enctype = 'multipart/form-data' name = 'upload-article-form'>
    <input type = 'text' placeholder = 'Article Title' className = 'art-title' onChange = {(e)=>{
        setArtTitle(e.target.value);
    }}/><br />
    <textarea placeholder = 'Article Content' className = 'art-content' onChange = {(e)=>{
        setArtContent(e.target.value);
    }}></textarea><br />

    <div className='image-preview'>
        {
            imagePreview && <img src = {imagePreview} style = {{maxWidth: "200px"}}/>
        }
        
    </div>

    <input type = 'button' value = 'Add Image' onClick = {addPostImage}/>
    <input type = 'file'  name = 'image' id = "img-upload" className = 'img-upload' ref = {fileUploadRef}
    onChange = {uploadPostImage} />
    <input type = 'submit' value = 'Upload' onClick = {makePost}/>
    </form>
</section>
</section>
<WhiteFooter />
</>
);

}
export default Dashboard;

下面是我的节点代码

const express = require("express");

const app = express();
const cors = require("cors");
const User = require('./models/user.model.js');
const fs = require("fs");
// const formidable = require("formidable");
const path = require("path");
const multer = require("multer");

const uploadPath = "../carefu_watchers/src/uploads/";
const serverUploadLocation = "images/";

const storage = multer.diskStorage({
    destination: (req, file, cb)=>{
        cb(null, uploadPath)
    }, 
    filename: (req, file, cb)=>{
        console.log(file);
        cb(null, Date.now() + path.extname(file.originalname));
    }
});



const uploadImage = multer({storage : storage});
app.use(express.json());


//This is the api being called by react
app.post("/api/multer-photo-upload", uploadImage.single("form-image"), (req, res)=>{
   res.send("You have hit the api");
});

// APP LISTINING AT THIS PORT
app.listen(1337, ()=>{
    console.log("App started on port 1337");
});
8ehkhllq

8ehkhllq1#

由于您使用的是对象属性简写{fd},因此它不会被解析,因此只需使用fd
试试这个:

const response = await axios.post("http://localhost:1337/api/multer-photo-upload", fd);

相关问题