Phoenix file upload

Hey guys :grin:

I’m having a problem that I believe someone smarter than me could point me in the right direction.
I have Phoenix backing up an API, with the following router:

scope "/api", MyApp do
  pipe_through :api
  resources "/users", UserController, except: [:new, :edit] do
    resources "/files", FileController, except: [:new, :edit]
  end
end

The :api pipeline is a standard api pipeline, i.e. :accepts ["json"].
The problem is that, in the FileController, I need to make a file upload. But everytime I post the file with multipart, I keep getting this error:

[debug] ** (Plug.Parsers.ParseError) malformed request, got MatchError with message no match of right hand side value: false
    (cowboy) src/cowboy_req.erl:735: :cowboy_req.init_multipart/1
    (cowboy) src/cowboy_req.erl:673: :cowboy_req.part/2
    (plug) lib/plug/adapters/cowboy/conn.ex:71: Plug.Adapters.Cowboy.Conn.parse_req_multipart/3

The FileController is a standard generated phoenix controller.
In the guides, the tutorial uses a HTML page to send in the file via FormData, and I’m sending them via Postman.

Thanks for your time!

5 Likes

Two thing syou can do:

  1. Send file as part of JSON request. I use HTML5 fetch API and handle file uploads using javascript in something like this:

     onFileSelected(event) {
       var input = event.target;
       var data = new FormData();
       data.append('myfile', input.files[0]);
       var self = this;
      
      this.setState({uploading: true, error: false});
    
     fetch('/api/files', {
       body: data,
       credentials: 'same-origin',
       method: "POST"
     }).then(function(response1) {
     ...
     }
    

Adjust to your needs.

or 2. Debug your actual problem :wink:

@nubunto when you put it into browser pipeline, does it work?

5 Likes

@nubunto
I am dilling with the same situation.
Have you figured it out?

1 Like