Ajax File Upload

<%- if @topic_view.topic.tags.present? %>
<%= t 'js.tagging.tags' %>: <%- @topic_view.topic.tags.each do |t| %> <%= t %> <%- end %>
<% end %>

Silverstripe Version: 4.7

Question:

I’ve been trying to do an ajax file upload using FormData in javascript, but I’m getting nothing on the server side.

The form is just a bunch of TextFields & an UploadField.

This is the JS method:

  saveForm(e) {
    e.preventDefault();
    const url = '/location-edit/save';
    const form = e.target;

    if(!form.reportValidity()) {
      return;
    }
    const data = new FormData(form);

    return fetch(url, {
      method: 'POST',
      body: data
    })
    .then(response => response.text())
    .then(data => {
      console.log(data);
    })
  }

What do I need to do on the server side to receive the file upload data? I’m stumped and there is very little information online.

Thanks

I have made progress. It seems the Silverstripe UploadField doesn’t have a ‘name’ attribute, which seems a bit odd to me.
I have created a workaround by adding a name attribute with JS before the form is submitted, and it works, but it seems a but hacky.
Is there something else I should be doing to make this work?

You might have better results using a FileField instead of an UploadField. The latter is designed with work with some specific JS, etc. so might be causing problems if that’s not present.

Ah, brilliant.
That fixed the issue, thanks.

1 Like