2

我正在尝试上传 CSV 文件并将其解析为最终将存储到数据库中的表。我在玩 Yesod 的文件上传示例,但我似乎无法让它与最新版本的 Yesod 一起工作。我正在使用Yesod 1.2.5.2 and GHC 7.6.3 on Ubuntu 14.04.

下面是我的代码

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

这是我想得到你帮助的部分:

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

一旦我有了 ByteString,我将使用 Data.Csv 来解析它:decode NoHeader s :: Either String (Vector (Vector ByteString))

有人可以让我知道如何从上传的文件中获取文件内容吗?我不需要将文件存储在磁盘上。

谢谢!

4

1 回答 1

3

这就是我所做的:

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 ...

对不起,我是用手机发的。

于 2014-04-30T00:12:56.037 回答