简体   繁体   English

我正在尝试在 node.js 后端使用 multer 上传文件并在前端对 js 做出反应,但它在公用文件夹中的 multer 的后端不起作用

[英]I'm trying to upload files with multer in node.js backend and react js in frontend but it doesn't work in back side with multer in public folder

frontend with React.js looks good i saw the other people who did same thing as i did but i don't know where is the problem?带有 React.js 的前端看起来不错,我看到其他人和我做同样事情的人,但我不知道问题出在哪里? anyone can help me ?任何人都可以帮助我吗?

    const [cours, setCours] = useState([]);
    const [description, setDescription] = useState("")
    const [title, setTitle] = useState("")
    const coursHandle = (e) => { setCours([e.target.files]) }

    const onsubmit = async (e) => {
       e.preventDefault();

       const formData = new FormData();
       formData.append("description", description);
       formData.append("title", title);
       // cours.forEach((elem) => { formData.append("cours", elem) });
       formData.append("cours", cours)
       // for (let i = 0; i < cours.length; i++) {
       //     formData.append("cours", cours[i])
       // }
       await axios.post("http://localhost:5000/upload", formData)
           .then((res) => console.log("successfully file post", res)).catch((err) => 
            console.log("error with file post", err))
   }

and backend with multer is here this code is in my app.js app.use(express.static(path.join(__dirname, 'public')));和 multer 的后端在这里这段代码在我的 app.js app.use(express.static(path.join(__dirname, 'public'))); and the public folder is the same place as app.js并且public文件夹和app.js在同一个地方

const multer = require("multer");
const path = require("path");

const MIME_TYPES = {
    "file/pdf": "pdf",
    "file/docx": "docx",
    "file/txt": "txt",
    "file/png": "png",
    "file/jpeg": "jpg",
    "file/jpg": "jpg",
}

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "public");
    },
    filename: (req, file, cb) => {
        const nameObject = path.parse(file.originalname);
        // const nameObject = file.originalname.split(' ').join('_');
        const extension = MIME_TYPES[file.mimetype];
        cb(null, nameObject.name.split(" ").join("_") + Date.now() + "." + extension);
    }
})

module.exports = { multerUpload: multer({ storage: fileStorage }).single("file") }

In last line在最后一行

module.exports = { multerUpload: multer({ storage: fileStorage }).single("file")

the argument under single is file , but in your frontend form there is no input with name file maybe you have to change the argument of single function from file to cours single 下的参数是file ,但是在您的前端表单中没有名称为 file 的输入,也许您必须将单个 function 的参数从file更改为cours

I found the answer for my question,我找到了我的问题的答案,

formData.append("cours", cours)  

Here the key name as i try to send is "cours" and:这里我尝试发送的关键名称是“cours”,并且:

module.exports = { multerUpload: multer({ storage: fileStorage }).single("file") 

Here the key name for single function is "file":!这里单个 function 的键名是“文件”:! that was a first problem and another one was this :这是第一个问题,另一个是:

I've forgoten to add this line in my tag !我忘记在我的标签中添加这一行!

encType="multipart/form-data"

And finally my multer js is:最后我的 multer js 是:

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, "public/files");
    },
    filename: (req, file, cb) => {
        console.log("filename :", file);
        const nameObject = path.parse(file.originalname);
        cb(null, nameObject.name.split(" ").join("_") + Date.now() + 
     nameObject.ext);
   }
})

module.exports = { multerUpload: multer({ storage: fileStorage }).array("cours") } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM