【问题标题】:req.file is undefined when uploading image from front end从前端上传图片时 req.file 未定义
【发布时间】:2022-03-07 23:56:16
【问题描述】:

我检查了其他类似的帖子,但它仍然无法正常工作:它在 console.log 时给我未定义。我还根据其他帖子定义了 multer 中间件,所以我不知道发生了什么。但是当我通过邮递员上传图片时,它可以返回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"})
        }
        
        
    }
}

【问题讨论】:

  • 您根本没有上传文件。您已在 FormDataprofile 键下添加了一个 JavaScript 对象。它将被序列化为字符串"[object Object]"。你确定你不只是想发布 JSON 吗?请参阅Using FormData Objects 获取指南

标签: javascript node.js reactjs axios multer


【解决方案1】:

创建这个函数(上传到 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测试功能,文件已上传

  注意:不要忘记和 请记住,这只是另一种选择,还有很多方式我希望你能理解,我希望它对你有用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2021-10-30
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多