Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot upload files received using multer #334

Closed
dzkb opened this issue Mar 28, 2022 · 1 comment
Closed

Cannot upload files received using multer #334

dzkb opened this issue Mar 28, 2022 · 1 comment

Comments

@dzkb
Copy link

dzkb commented Mar 28, 2022

Hi,

first of all thanks for such a great project!

I have a very specific use case where my express.js app receives a file and then forwards it to a GraphQL API. Based on the example from the quickstart, I came up with code like this:

app.post('/endpoint', upload.single('file'), function (req, res, next) {
    let file = req.file
    const mutation = gql`
    mutation($file: Upload!){
        uploadFile(file: $file) {
            responseField
        }
    `

    request("http://localhost:8000/graphql", mutation, {
        file: file
    })
})

The problem is that when I try to run the upload (by sending a request with a file to /endpoint), graphql-request sends a JSON payload of multer's representation of the file, instead of the file itself, and my GraphQL server (Python, strawberry-based) refuses to parse that. I also tried to pass a buffer (file.buffer) instead of a file, but no luck either. Note that replacing the following part:

    request("http://localhost:8000/graphql", mutation, {
        file: file
    })

with

    request("http://localhost:8000/graphql", mutation, {
        file: createReadStream('./file'), // from fs
    })

works just fine.

I believe the underlying issue is that the FormData object, constructed before sending the request, doesn't understand multer's representation of a file. I managed to get around that by constructing my own FormData object and sending it without using graphql-request.

// graphql-multipart-request-spec related
let operations = {
  "query": mutation,
  "variables": {
    "file": null
  }
}
let requestMap = {
  "file": ["variables.file"]
}

let formData = new FormData()
formData.append("operations", JSON.stringify(operations))
formData.append("map", JSON.stringify(requestMap))
formData.append("file", file.buffer, { filename: "file", contentType: "audio/wav" }) // setting the filename and contentType seems to be enough - it's audio/wav in my case

Is this the expected behavior? Or is there any other way to pass a buffer/file to request so that graphql-reqest understand that it's actually a file?

Thanks!

@jasonkuhrt
Copy link
Member

#500

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants