req.file 前端上传图片时未定义

req.file is undefined when uploading image from front end

我已经检查了其他类似的 post,但它仍然无法正常工作:它在 console.log 时给我未定义。我还根据其他 post 定义了 multer 中间件,所以我不知道发生了什么。但是当我通过 postman 上传图片时,它会按预期返回 201。感谢您的帮助!

ReactJS 函数:

const UploadImageToBackend = async () => {
  console.log(UploadedImage) //UploadedImage is something like /Users/.../.jpg
  let formData = new FormData()
  formData.append('profile', 
    {name : new Date() + "_profile", uri: UploadedImage, type:'image/jpg'})
  
  try{
    const res = await client.post('/upload-avatar',formData, {
      headers:{
        Accept : 'application/json',
        authorization: 'JWT some JWT'
      },
    })
    console.log(res.data)
  }catch(error){
    console.log(error.response.data) //gives "Error while uploading Image, try after some time" error
  }
  
}

后端路由:

const fileFilter = (req,file,callback) => {
    if (file.mimetype.startsWith('image')){
        callback(null,true)
    }else{
        callback('invalid image file', false)
    }
}
const storage = multer.diskStorage({})
const uploads = multer({storage, fileFilter})
router.post('/upload-avatar',isAuth, uploads.single('profile'),uploadProfile)

后端上传功能(到Cloudinary)

exports.uploadProfile = async (req,res)=>{
    const user = req.user
    if (!user){
        return res.status(401).json({success:false,message:"unauthorized access!"})
    }else{
        console.log(req.file.path) //undefined
        try{
            const upload_result = await cloudinary.uploader.upload(req.file.path, {
                public_id: `${user._id}_profile`,
                width:500,
                height:500,
                crop: 'fill'
            })
            await User.findByIdAndUpdate(user._id, {avatar: upload_result.url})
            res.status(201).json({success:true,message: "Profile picture successfully uploaded"})
            
        }catch (error){
            res.status(500).json({success:false,message: 
        "Error while uploading Image, try after some time"})
        }
        
        
    }
}

创建这个函数(上传到 Cloudinary),例如“lib/cloudinary.js”并添加此代码:

import cloudinary from "cloudinary";

cloudinary.config({
   cloud_name: "YOUR_CLOUD_NAME",
   api_key: "YOUR_API_KEY",
   api_secret: "YOUR_API_SECRET",
});

const upload = {};

upload.subir = async (file) => {
  try {
    const res = await cloudinary.uploader.upload(file);
    // return the secure url
    return res.secure_url;
  } catch (error) {
    return error;
  }
}

export default upload;

现在在您的控制器中,例如添加此代码,不要忘记安装 express-fileupload:

import cloudinary from "../lib/cloudinary.js";

const upload = {};

upload.uploadProfile = async (req, res) => {
   const a_file = await cloudinary.subir(req.files.a_file.tempFilePath);
   // show the secure url, e.g.: 
   // https://res.cloudinary.com/xx/image/upload/yy/winter.jpg
   console.log(a_file);
   // ... more code
}

export default upload;

现在在您的主应用程序中,例如“app.js”,添加此代码以使用 express 中间件上传文件:

import express from 'express';
import fileUpload from 'express-fileupload';

const app = express();

app.use(express.json());
app.use(express.urlencoded({extended: true}));
app.use(fileUpload({useTempFiles: true}));
// ...  more code

使用postman测试功能,文件已上传

  NOTE: Do not forget and remember that this only is an alternative, exist anothers many ways i hope you understand and i hope it works for you