Django Rest Framework: Upload file via AJAX

限于喜欢 提交于 2019-12-01 21:13:08

Ok, I can't exactly explain why, but it seems like var formData = new FormData($(this)); is not enough alone, it needs to be explicitly appended, because reasons? If anyone can explain, please do.

The working code:

<form action="http://localhost:8000/accounts/api/image/"
      method="put"
      enctype="multipart/form-data">
    <input name="image" type="file" id="image">
    <input type="submit">
</form>

<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

<script>
    $('form').submit(function(e) {
        var formData = new FormData($(this));
        formData.append('image', $('#image')[0].files[0]);
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: formData,
            headers: {'Authorization': 'Token mytoken'},
            cache: false,
            contentType: false,
            processData: false,
            success: function() { alert('it works') },
        });
        e.preventDefault();
    });
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!