【问题标题】:Retrieving a request within an express controller to store file在快速控制器中检索请求以存储文件
【发布时间】:2022-01-24 16:42:53
【问题描述】:

我目前正在构建一个 express 后端。我创建了一个路由器和控制器系统来处理来自服务器的每个请求。我目前正在尝试将与配置文件一起发送的图像文件保存为个人资料图片。我目前正在将multer 集成到我的后端。我设置了 multer 目标,但我不确定如何获取通过的请求,以便在请求到达控制器之前实际保存文件。

我的 app.js:

...
// app.use(logger('dev'))
app.use(cors());
app.use(cookieParser())
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : true }));
app.use(session({
  secret: 'helloworld',
  cookie: {maxAge: 60000},
  saveUninitialized: false,
}))
app.use(morgan('dev'))
app.use(fileUpload());

app.use('/api/auth', AuthenticationRouter)
app.use('/api/user', UserRouter)
app.use('/api/profile', ProfileRouter)
app.use('/api/follow', FollowRouter)
app.use('/api/post', PostRouter)
app.use('/api/like', LikeRouter)
app.use('/api/edit', EditRouter)
app.use('/api/download', DownloadRouter)
app.use('/api/comment', CommentRouter)

以下是路由器页面。这就是我试图获取请求并保存随请求发送的文件的地方。我不确定此时如何注入和获取请求对象 路由器:

const multer = require('multer')
const upload = multer({dest:'../client/static/images/ProfilePictures'})

const router = require("express").Router()
const profileController = require("../../controllers/UserControllers/ProfileController.js");

router
  .route('/')
  .get(profileController.get)
  .post(upload,single(''), profileController.post)
  .delete(profileController.delete)
  .patch(profileController.patch)

module.exports = router;

控制器:

const Profile = require("../../models/UserModels/Profiles.js")
const User = require('../../models/UserModels/Users.js')

const profileController = {
  post:(req, res) => {
    console.log(req.files.profile_pic.name)
    let body = req.body
    let file = req.files.profile_pic
    Profile.create({
      profile_pic: file.name,
      f_name: body.f_name,
      l_name: body.l_name,
      bio: body.bio,
      location: body.location,
      sm_facebook: body.sm_facebook,
      sm_instagram: body.sm_instagram,
      sm_twitter: body.sm_twitter,
      sm_website: body.sm_website,
      followers: body.followers,
      following: body.following,
      photos: body.photos,
      downloads: body.downloads,
      edits: body.edits,
      userId: body.userId
    })
    .then((data) => {
      res.send(data).status(200)
    })
    .catch((err) => {
      console.error(err)
      res.send(err).status(400)
    })
  },

【问题讨论】:

    标签: javascript node.js express multer


    【解决方案1】:

    你有一个错字。应该是upload.single(''),而不是upload,single('')

    Multer 将自动解析图像并使用图像上传数据填充req.file。但是,在您的控制器中,您正尝试访问 req.files。因此,如果您要上传多个文件,我建议您从upload.singe('') 切换到upload.any(),因为upload.any() 将填充req.files 而不是req.file

    你可以这样改变你的路由器:

    router
      .route('/')
      .get(profileController.get)
      .post(upload.any(), profileController.post)
      .delete(profileController.delete)
      .patch(profileController.patch)
    
    

    你可以像这样改变你的控制器:

    const profileController = {
      post:(req, res) => {
        console.log(req.files)
        let file = req.files[0];
        ...
      },
    }
    
    

    【讨论】:

    • 好的,所以我的理解是,由于我在控制器中定义了 multer 并设置了目标,multer 会自动将文件保存在我设置的目标中。我真的不需要获取文件名来存储它。我可以做upload.any()。还是我需要在upload.any() 中有文件名。
    猜你喜欢
    • 2021-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-09
    • 1970-01-01
    • 2019-07-14
    相关资源
    最近更新 更多