【问题标题】:Express file upload: req.files is undefined快速文件上传:req.files 未定义
【发布时间】:2021-10-15 11:19:48
【问题描述】:

我正在使用名为 express-fileupload 的库进行文件处理中间磨损。但是当我做console.log.log(req.files) 时,它说未定义。我在 chrome 开发工具中检查了请求标头,它显示为 img/png,但 express 显示为未定义。

这是我的客户端:

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"})
}

【问题讨论】:

    标签: javascript node.js typescript express file-upload


    【解决方案1】:

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

    您正在发布一个普通文件。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-06
      • 2018-08-04
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 2014-05-31
      相关资源
      最近更新 更多