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?
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?
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: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:
Oh, and because it's a record, following example should work even if the definition gets updated once again:
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.
The answer really depend on the content of "File". for example if the file content a string with respecting erlang syntax such as:
can be read with this code:
[Edit]
the Erlang libraries use most of the time tuple as return value. It can help to manage the normal case and error cases. In the previous code, all lines are "pattern matched" to the success case only. That means that it will crash if any of the operation fails. If the surrounding code cath the error you will be able to manage the error case, otherwise the process will simply die reporting a badmatch error.
I chose this implementation because at this level of code, there is nothing that can be done to deal with an error.
{{badmatch,{error,enoent}}
simply means that the return value offile:read_file(File)
is not of the form{ok,B}
as expected, but is{error,enoent}
, which means that the fileFile
does not exist in the current path.extract of the documentation
In my opinion the calling code should manage this case if it is a real use case, for example
File
comes from a user interface, or let the error unmanaged if this case should not happen. In your case you could do