快速文件上传:req.files 未定义

Express file upload: req.files is undefined

我正在使用名为 express-fileupload 的库来处理文件中间件。但是当我做 console.log.log(req.files) 它说未定义。我在 chrome 开发工具中检查了请求 headers,它说 img/png 但快递说它未定义。

这是我的客户端:

public static async upload(data: Upload){
      const track = data.track
      const artwork = data.artwork
      if(track && artwork){
          try{
              await Req.upload("/api/u/music/upload", track)
              await Req.upload("api/u/music/upload", artwork)
          }catch(err){
              console.log(err)
          }
      }
 }
 
 /*req class*/
 
 export class Req {
    public static async upload(url: string, file: File|null|undefined){
      const response = await fetch(url, { // Your POST endpoint
        method: 'POST',
        headers: {
          // Content-Type may need to be completely **omitted**
          // or you may need something
          "CSRF-Token": <string>Cookies.get("XSRF-TOKEN"),
        },
        body: file // This is your file object
      })
      return await response.json()
    }
}

在我的服务器端:

app.use(cors())
app.use(bodyParser.urlencoded({extended : true, limit: "100mb"}));
app.use(bodyParser.json({limit: '100mb'}));
app.use(express.static(path.join('build')))
app.use(cookieParser())
app.use(fileUpload())
app.use(csrf({cookie: true}))


export const uploadMusic = async (req: Request, res: Response)=>{
    console.log(req.files) //undefined
    res.send({"upload_status": "ok"})
}

您正在使用的模块(以及 Bona Ws 推荐的模块)希望您 POST 一个 multipart/form-data 正文,其中文件是其中的一部分。

您发布的是普通文件。

使用 a FormData object 生成多部分请求。

const body = new FormData();
body.append("key", file);