Chris Stryczynski
Chris Stryczynski

Reputation: 34041

wreq how to combine file upload with post form fields?

How can I combine Part with [(ByteString, ByteString)] (ordinary form input)?

partFile :: Text -> FilePath -> Part

They're both part of the Postable typeclass http://hackage.haskell.org/package/wreq-0.5.3.2/docs/Network-Wreq-Types.html#t:Postable

I'm going to take a guess it's something that can be done with a lens combinator?

Full code below where I'm sending two request - one with post form fields - the other with a file upload.

app.cabal

cabal-version: 1.12    
name:           app
version:        0.1.0.0
author:         CabalSaneDefault
maintainer:     nobody
license:        BSD3
build-type:     Simple

executable app-test
  main-is: Test.hs
  other-modules:
      Paths_app
  hs-source-dirs:
      src
  build-depends:
      base
    , bytestring
    , lens
    , wreq
  default-language: Haskell2010

src/Test.hs

{-# Language OverloadedStrings #-}
module Test where

import Network.Wreq
import Control.Lens
import Data.ByteString (ByteString)
import Data.ByteString.Lazy.Char8 (putStrLn)
import qualified Network.Wreq.Session as S

main :: IO ()
main = do
  let rootUrl = "http://localhost:80"
  print "test"
  sess <- S.newSession
  x <- S.customHistoriedPayloadMethodWith
    "POST"
    defaults
    sess
    (rootUrl ++ "/post")
    ([("test","chris"), ("test2", "chris2")] :: [(ByteString, ByteString)])
  Data.ByteString.Lazy.Char8.putStrLn $ (x ^. hrFinalResponse ^. responseBody)
  print "--------------------------------------------------"
  x' <- S.customHistoriedPayloadMethodWith
    "POST"
    defaults
    sess
    (rootUrl ++ "/post")
    (
      (partFile "" "app.cabal")
    )
  Data.ByteString.Lazy.Char8.putStrLn $ (x' ^. hrFinalResponse ^. responseBody)

Upvotes: 1

Views: 105

Answers (1)

Chris Stryczynski
Chris Stryczynski

Reputation: 34041

http://hackage.haskell.org/package/http-client-0.6.4/docs/Network-HTTP-Client-MultipartFormData.html#v:partBS to create a Part from a ByteString and then we can post a [Part] because it's an instance of Postable.

  x' <- S.customHistoriedPayloadMethodWith
    "POST"
    defaults
    sess
    (rootUrl ++ "/post")
    (
      [
        (partFile "" "app.cabal")
      , partBS "test" "chris"
      , partBS "test2" "chris2"
    ]
    )

Upvotes: 0

Related Questions