Handling Binary (excel) file in Multi-data Post data in Suave.IO

168 views Asked by At

I am trying to build a simple Suave.IO application to centralize the sending of emails. Currently the application has one endpoint that takes subject, body, recipients, attachments, and sender as form data and turns them into an EWS email message from a logging email account.

Everything works as intended in most cases, but I get a file corruption issue when one of the attachments is an excel file. In those cases, the file seems to get corrupted.

Currently, I am filtering the request.multipartFields down to only the ones that are marked as attachment files, and then doing this:

for (fileField: (string*string)) in fileFields do
            let fname = (fst fileField)
            let fpath = "uploadedFiles\\" + fname
            File.WriteAllBytes(fpath, Encoding.ASCII.GetBytes (snd fileField)) |> ignore

The file path and the attachment names are then fed into the EWS message before sending.

Again, this seems to work with all attachments except attachments with binary. It seems like Suave.IO automatically encodes all multiPartFields as (string*string), which may require special handling when it's binary data.

How should I handle upload of binary files?

Thanks all in advance.

1

There are 1 answers

0
shanglun On

It looks like the issue was one of encoding. I was testing using python's request interface, and by default the files are encoded as multipart/form-data. By specifying a specific encoding for each file, I was able to help the server identify the incoming data as a file.

instead of

requests.post(url, data=data, files={filename: open(filepath, 'rb')})

I needed to make it

requests.post(url, data=data, files={filename: (filename, open(filepath, 'rb'), mimetypes.guess(filepath)})

With the second python script, files do end up in the files section of the request and I was able to save the excel file without corruption.