从node.js文件发送包含pdf文件的DataForm

时间:2019-04-09 21:13:14

标签: node.js axios multipartform-data

我正在尝试将包含pdf文件的FormData从node.js脚本发送到服务器。该请求失败,并以状态码400作为响应。在服务器端,他似乎没有将数据视为pdf文件,或者似乎未定义整个数据。

这是我的node.js脚本所做的事情:(我尝试了其他方式发送请求,但没有成功)

import axios from "axios"
import fs from "fs-extra"
import FormData from 'form-data'

const formData = new FormData()
const diplomaBuffer = await fs.readFile(`../data/fake/foo`+i+`.pdf`)

formData.append("diploma", diplomaBuffer)
formData.append("diplomaId", 1)

axios({
  method: 'post',
  processData: false,
  contentType: 'multipart/form-data',
  cache: false,
  url: 'http://localhost:8080/certificates',
  data: formData,
  config: { headers: formData.getHeaders() }
})

// const response = await axios
// .post(`http://localhost:8080/certificates`, {
//     body: formData
// })

// const response = await axios
// .post(`http://localhost:8080/certificates`
//      , formData
//      , {headers: formData.getHeaders()})

这是在服务器端调用的函数:

app.post('/certificates', async (req, res) => {
        const files = req.files

        if(!files || !files.diploma || !files.diplomaId) {
            res.status(400).send(new Error("No file provided"))
        }

        if(files.diploma.mimetype !== "application/pdf") {
            res.status(400).send(new Error("diploma is not a pdf"))
        }

        // operations made with the received pdf (not relevant for the question)
        const certificateId = uniqid()
        const outputDiploma = `data/diplomas/${certificateId}.pdf`

        await Promise.all([
            fs.writeFile(outputDiploma, files.diploma.data),
        ])

        await pdf.sign(outputDiploma, `${sha("sha256").update(certificateId + diplomaSecret).digest("hex")} : ${date()}`)

        const diplomaBuffer = await fs.readFile(outputDiploma)
        const certificate_hash = verify_pdf.hashBuffer(diplomaBuffer)

        const certificateRegistry = await app.bizNetworkConnection.getAssetRegistry("consortium.supchain.assets.Certificate")
        const certificate = app.factory.newResource("consortium.supchain.assets", "Certificate", certificateId)
        certificate.diploma = app.factory.newRelationship("consortium.supchain.assets", "Diploma", req.body.diplomaId)
        certificate.hashInfo = certificate_hash
        await app.registry.certificate.add(certificate)

        res.status(200).send("ok")
    })

0 个答案:

没有答案