Question

I am trying to upload a CSV file and parse it into a table that will eventually be stored into a DB. I was playing around with Yesod's File Upload example but I cannot seem to make it work with the latest version of Yesod. I am using Yesod 1.2.5.2 and GHC 7.6.3 on Ubuntu 14.04.

Below is my code

fileUploadForm :: Form ((Key Account), FileInfo)
fileUploadForm = renderDivs $ (,)
    <$> areq (selectField accounts) "Account" Nothing
    <*> fileAFormReq "Choose a file"
    where
    accounts = do
        entities <- runDB $ selectList [] [Asc AccountName]
        optionsPairs $ map (\s -> (accountName $ entityVal s, entityKey s)) entities

getUploadTransactionR :: Handler Html
getUploadTransactionR = do
  (widget, enctype) <- generateFormPost fileUploadForm
  defaultLayout $ do
       setTitle "Upload new file."
       $(widgetFile "upload_transactions")

This is the part I would like to get your help:

postUploadTransactionR :: Handler Html
postUploadTransactionR = do
  ((result, widget), enctype) <- runFormPost fileUploadForm
  case result of
    FormSuccess (account, fi) -> do
                     -- ??? I would like to get the contents of fi and send it to a CSV parser. 
                 -- (fileSourceRaw fi)??? 

                 redirect (HomeR)
    _ -> return ()

  defaultLayout $ do
       $(widgetFile "upload_transactions")

Once I have the ByteString, I would be using Data.Csv to parse it as such: decode NoHeader s :: Either String (Vector (Vector ByteString))

Could someone let me know how I can get the file contents from the uploaded file? I don't need to store the file on disk.

Thanks!

Was it helpful?

Solution

This is what I do:

postSomethingR = do
  ((res, _), _) <- runFormPost form
  case res of
    FormSuccess (account, file) -> do
      bytes <- runResourceT $ fileSource file $$ sinkLbs
      -- Parse the ByteString in another thread
      parseHandler <- handlerToIO
      liftIO $ forkIO $ parseHandler $ do
        case CSV.parseCSV csvSettings (decodeUtf8 . toStrict $ bytes) of
          Left err -> ...
          Right vector -> runDB $ do ...

Sorry, I'm posting this from a cellphone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top