Marian Dziubiak
Marian Dziubiak

Reputation: 174

Upload file in a Suave application

I've recently started creating a website with F# and Suave for a project at my University. One of the things I need is to let the user upload a file via the website, which I will then parse.

What I have right now is

let post =
   let ``process`` httpRequest =
      use reader = File.OpenText httpRequest.files.Head.tempFilePath
      // do parsing and save to database
   request ``process``

In my HTML I have a simple form

<form action="/parse" method="POST">
    <div>
        <input type="file" name="file">
    </div>
    <div>
        <button>Send</button>
    </div>
</form>

And during the processing of the POST request via the post method I get the following exception

[22:45:30 ERR] request failed
System.InvalidOperationException: The input list was empty.
  at Microsoft.FSharp.Collections.FSharpList`1[T].get_Head () <0x41494340 + 0x0007b> in <filename unknown>:0
  at [email protected] (Suave.HttpRequest httpRequest) <0x41493e10 + 0x0003b> in <filename unknown>:0
  at Microsoft.FSharp.Core.FSharpFunc`2[T,TResult].InvokeFast[V] (Microsoft.FSharp.Core.FSharpFunc`2 func, Microsoft.FSharp.Core.T arg1, Microsoft.FSharp.Core.TResult arg2) <0x4143c6a0 + 0x00099> in <filename unknown>:0
  at [email protected] (Suave.HttpContext context) <0x41493dc0 + 0x0002f> in <filename unknown>:0
  at Suave.WebPart+bind@14-5[a,b].Invoke (Microsoft.FSharp.Core.FSharpOption`1 _arg1) <0x41472a10 + 0x00044> in <filename unknown>:0
  at Microsoft.FSharp.Control.AsyncBuilderImpl+args@835-1[a,b].Invoke (a a) <0x41435c60 + 0x000af> in <filename unknown>:0

Which means that there is no file in the httpRequest.files list.

I wasn't able to find any information on how to access the uploaded file, or if it is uploaded at all. I checked the content of HTTP Request sent by my browser with Fiddler and all I could see there was

file=myFile.txt

So is the file being uploaded? Am I accessing it correctly?

Note: I'm using Suave 2.0.0

Upvotes: 4

Views: 620

Answers (1)

Marian Dziubiak
Marian Dziubiak

Reputation: 174

Ok, I found what I was missing. To post a file the form must have an additional parameter like this

<form action="/parse" method="POST" enctype="multipart/form-data">

That way the content of the file is sent alongside the HTTP Request in the Content section.

(found out via https://searchcode.com/codesearch/view/7502482/)

Upvotes: 6

Related Questions