Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file to the server using Yesod

I'm trying to write a form that allows users to upload a file to my server. I saw Yesod uses fileAFormReq for such a functionality but was unable to get it to work, running into compilation errors, the latest of which was: "No instance for (RenderMessage MySite t)" Any stripped down example for how to use it will be highly appreciated. Thanks, Uri

like image 883
Uri Barenholz Avatar asked Sep 18 '11 09:09

Uri Barenholz


1 Answers

Update 13-Sep-2012:

There is an official maintained help page for file uploading here


Googling on the function fileAFormReq gave me this example.

I Made a minimal version of it with only the relevant parts.

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-}
import Yesod.Core
import Yesod.Form
import Yesod.Form.MassInput
import Control.Applicative
import Data.Text (Text, pack)
import Network.Wai.Handler.Warp (run)
import Data.Time (utctDay, getCurrentTime)
import qualified Data.Text as T
import Control.Monad.IO.Class (liftIO)

mkYesod "HelloForms" [parseRoutes|
/file FileR GET POST
|]

data HelloForms = HelloForms

instance RenderMessage HelloForms FormMessage where
    renderMessage _ _ = defaultFormMessage

instance Yesod HelloForms where
    approot _ = ""


main = toWaiApp HelloForms >>= run 3000

fileForm = renderTable $ pure (,)
    <*> fileAFormReq "Required file"
    <*> fileAFormOpt "Optional file"

getFileR = do
    ((res, form), enctype) <- runFormPost fileForm
    defaultLayout [whamlet|
<p>Result: #{show res}
<form method=post enctype=#{enctype}>
    <table>
        ^{form}
    <tr>
        <td>
            <input type=submit>
|]

postFileR = getFileR

runhaskell this and then visit http://localhost:3000/file in your browser.

Hope this helps. :)


Edit:

Oh wait, it's obvious what you're missing. As the compilation error just said, you're missing a RenderMessage instance for your Foundation.

I know recent efforts for i18n have changed the forms-package slightly. If you're using the latest version of yesod, check this out.

The code I pasted uses the old non-i18n (default means english) version of yesod-forms package.

like image 128
Tarrasch Avatar answered Sep 22 '22 04:09

Tarrasch