1

I'm trying to simply upload a file (and the name of the file) with/Django rest framework and REACT/Axios and I do not understand what I'm doing wrong.

I have this error:

request.response: "{"my_file":["No file was submitted."]}"

This is my REACT frontend:

uploadFile = e => {
    e.preventDefault();
    let formData = new FormData();
    formData.append('my_file', e.target.files[0]);
    axios.post('http://127.0.0.1:8000/uploadFiles/', {
        formData,
        name: 'name',
        headers: {
            Accept: 'application/json, text/plain, */*',
            'Content-Type': 'multipart/form-data'
        },
    })
        .then(() => {
            console.log('All Done',);
        })
        .catch(error => {
            console.log('error.response: ', error.response);
        });
}

render() {
    return (
        <input
            type='file'
            onChange={this.uploadFile}
        />
    );
}

This is my Django REST backend with:

models.py:

def user_directory_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
    return 'user_{0}/{1}'.format(instance.user.id, filename)

class File(models.Model):
    my_file = models.FileField(upload_to=user_directory_path)
    name = models.CharField(null=False, max_length=50)
    upload_date = models.DateTimeField(auto_now_add=True)

serializers.py

class FileSerializer(serializers.ModelSerializer):

class Meta:
    model = File
    fields = (
        'id',
        'my_file',
        'name',
        'upload_date',
    )

views.py

class UploadFileView(views.APIView):
    parser_classes = (JSONParser, MultiPartParser, FormParser,)

    def post(self, request, *args, **kwargs):
        fileSerializer = FileSerializer(data=request.data)
        if fileSerializer.is_valid():
            fileSerializer.save()
            return Response(fileSerializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST)

I've had a lot of difficulties to write this code and I think I'm close to the end but I can't figure why this file isn't submitted.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Nico
  • 404
  • 6
  • 17

1 Answers1

0

Here are the modifications to make the upload work:

uploadFile = e => {
    let formData = new FormData();
    formData.append('my_file', e.target.files[0]);
    formData.append('name', 'var name here');
    const url = 'http://127.0.0.1:8000/uploadFiles/';
    const config = {
        headers: { 'content-type': 'multipart/form-data' }
    }
    axios.post(url, formData, config)
        .then(() => {
            console.log('All Done',);
        })
        .catch(error => {
            console.log('error: ', error);
            console.log('error.response: ', error.response);
        });
}

Source of inspiration

Nico
  • 404
  • 6
  • 17