postfile-ioerlangnitrogenchicagoboss

How to read from post param?


I need to parse text file. This file is in post param. I have code like this:

upload_file('POST', []) ->
    File = Req:post_param("file"),

What should I do next? How to parse it?


Solution

  • What's inside Req:post_param("file") ?

    You assume it's a path to a file: have you checked the value of File ?

    Anyway, it's Req:post_files/0 you are probably looking for:

    [{_, _FileName, TempLocation, _Size}|_] = Req:post_files(),
    {ok,Data} = file:read_file(TempLocation),
    

    It's also probably a Bad Idea to leave the file at it's temporary location, you'd better find a more suitable place to store them.


    It seems the uploaded_file record has 5 fields now (for 10 months by now).

    This is the updated example, with the fifth field:

    [{_, _FileName, TempLocation, _Size, _Name}|_] = Req:post_files(),
    {ok,Data} = file:read_file(TempLocation),
    

    Oh, and because it's a record, following example should work even if the definition gets updated once again:

    [File|_] = Req:post_files(),
    {ok,Data} = file:read_file(File#uploaded_file.temp_file),
    

    Another warning: the code above, as any erlanger will see, only deals with the first and, probably most of the times, only uploaded file. Should more files be uploaded at the same time, these would be ignored.