0

I want to submit a form to upload either a csv file or an excel file, and provide additional information provided in the form, e.g. text.

For defining the form and sending the request I use React Bootstrap with axios, and for the api I'm using Django 2.2 with rest-framework.

request.FILES is always an empty dict, even if I try setting the Content-Type header to multipart/form-data, and then additionally nothing is found in the post data of the request, and printing request.data.get('information') below shows None in the Django log. Please help, any support will be greatly appreciated.

See below for code snippets.

Form definition in render():

<form onSubmit={this.handleSubmit}>
    <FormGroup>
    <Form.Label>Upload file</Form.Label>
    <Form.Control type="file" onChange={this.handleFile}></Form.Control>
    </FormGroup>

    <Button block bssize="large" disabled={!this.validateForm()} type="submit">
    Submit
    </Button>
</form>

Handling file change:

handleFile = event => {
  event.preventDefault();

  const fileToUpload = event.target.files[0]
  this.setState({
    fileToUpload: fileToUpload
  })
}

Sending the request:

const payload = {
    file: this.state.fileToUpload,
    information: "somedata"
}

const contentType = "multipart/form-data"
let accessToken = token
var headers = {"Authorization" : `Bearer ${accessToken}`}
headers['Content-Type'] = contentType
const response = await axios({
    method: "post",
    data: payload,
    url: url,
    headers: headers
});

Django endpoint definition:

class RegisterData(views.APIView):
    parser_classes = (parsers.JSONParser, parsers.MultiPartParser)

    def post(self, request):
        for file in request.FILES.values():
            print(file)

        info = request.data.get('information')
        print(info)
        return Response({"success": "Good job, buddy"})
Simen Russnes
  • 2,002
  • 2
  • 26
  • 56
  • 1
    Check that your call is correct for axios file uploads: https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios – Sergio Pulgarin Aug 15 '19 at 14:40
  • Oh, yes. I was sending the post data as a simple dictionary, but when I changed it to a FormData object it appears to work! – Simen Russnes Aug 15 '19 at 14:50

1 Answers1

0

The answer is in the comments but I'll put it here so it's more visible to users with these issues:

Check that you are using the correct data types and arguments for axios:

How to post a file from a form with Axios

Sergio Pulgarin
  • 869
  • 8
  • 20