Ad

Using Superagent To Submit A Form Via Ajax Containing An Image Value

- 1 answer

I've tried a few different methods and nothing seems to be submitting my icon file properly

request
  .post('/my/newapp')
  .type('multipart/form-data')
  .field('name', input.newAppName)
  .field('description', input.newAppDescription)
  .field('csrf', csrf.newApp)
  .attach('icon', this.refs.icon.value) // Doesn't save for some reason
  .end((err, res) => {...

For the submit above my request payload looks like:

------WebKitFormBoundarywygaaRkqk2Kr6zzJ
Content-Disposition: form-data; name="name"

afasfasfasf
------WebKitFormBoundarywygaaRkqk2Kr6zzJ
Content-Disposition: form-data; name="description"


------WebKitFormBoundarywygaaRkqk2Kr6zzJ
Content-Disposition: form-data; name="csrf"

16we7ncdfoyz5twnc1ilhg5pjgr6ze5s36153ffbf:aYCZkOQV6nxQq6mXWmCLOQ==
------WebKitFormBoundarywygaaRkqk2Kr6zzJ
Content-Disposition: form-data; name="icon"


------WebKitFormBoundarywygaaRkqk2Kr6zzJ--

But I get a 502 on my pyramid application: ValueError: Invalid boundary in multipart form: ''.

I've also tried to use FormData to no avail.

let formData = new FormData();
formData.append('name', input.newAppName);
formData.append('description', input.newAppDescription);
formData.append('csrf', csrf.newApp);
formData.append('icon', this.refs.icon.value);
request
  .post('/my/newapp')
  .type('form')
  .set('Content-Type', 'application/x-www-form-urlencoded')
  .send(formData)
  .end((err, res) => {...

Any insight is much appreciated. If I do a normal non-ajax form post it works fine.

Ad

Answer

Figured it out. I was using the wrong attribute when adding the icon to formData.

  handleSubmit(e) {
    e.preventDefault();
    let {input, csrf, setErrorModal} = this.props;
    let formData = new FormData();
    formData.append('name', input.newAppName);
    formData.append('description', input.newAppDescription);
    formData.append('csrf', csrf.newApp);
    formData.append('icon', this.refs.icon.files[0]);
    request
      .post('/my/newapp')
      .send(formData) // works now =-]
      .end((err, res) => {...
Ad
source: stackoverflow.com
Ad