NodeJS 从react native到multer的文件上传在我记录req.file时一直返回undefined

8gsdolmq  于 2023-01-12  发布在  Node.js
关注(0)|答案(1)|浏览(117)

由于某种原因,当我通过fetch使用表单数据发送图像时,服务器总是返回undefined。

let formData = new FormData()
let uri = "file:/data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Ftrivia-b38a8724-1083-4c3b-9706-78eed8b14ff9/ImagePicker/ff04888e-8619-420d-b80f-3ed97cebc25c.png"
const filetype = uri.split('.').pop()
let photoData = {
  name: `photo.${filetype}`,
  uri,
  type: filetype
}
formData.append('photo', photoData)
fetch('myUrl.com/upload', {
    method: 'POST',
    body: formData,
    headers:{
      'Accept': 'application/json',
      'Content-Type': 'multipart/form-data'
    },
  }).then(res => res.json())

下面是后端的代码:

const express = require("express");
const app = express();
const http = require('http').createServer(app)
let router  = express.Router()
const multer = require('multer')
const storage = multer.memoryStorage()
const multerUploads = multer({storage})

app.use(bodyParser.json())
const PORT = process.env.PORT || 3000


app.use((req, res, next) =>{
console.log(new Date().toString())
next()
})

router.post('/upload', multerUploads.single('photo'), (req, res) =>{
console.log(req.file)
})

app.use(router)
http.listen(PORT, () => console.log(`Server started at port ${PORT}`))

有什么问题吗?

yjghlzjz

yjghlzjz1#

只需删除'Content-Type': 'multipart/form-data'

fetch('myUrl.com/upload', {
    method: 'POST',
    body: formData,
    headers:{
      'Accept': 'application/json',
    },
  }).then(res => res.json())

相关问题