G
G
gromyko212020-10-23 08:22:21
JavaScript
gromyko21, 2020-10-23 08:22:21

Why am I getting NoneType when uploading a file from js to django?

I'm making a chat on channels. I want to be able to upload files. As I found out, you first need to get the file in js, then pass it to the python function to load this file into a folder, then return the path to this photo to the sockets. I do like this:

<input id="upload" type="file" onchange="selectFile()">

<script>
function selectFile() {
  e = document.getElementById('upload')
  if(e.files[0]) {
    let item = e.files[0];

    let filesize = item.size;
    let filesizeMB = (filesize / (1024 * 1024)).toFixed(2);
    if (filesizeMB >= 3) {
      alert('Максимальный размер фотографии 3 мб');
    } else {

var $input = $("#uploadimage");
    var fd = new FormData;


    fd.append('csrfmiddlewaretoken', '{{ csrf_token }}');
    fd.append('image_message', item);
    console.log(fd)
    $.ajax({
        url: '/chat/upload/',
        type: 'POST',
        data: fd,
        processData: false,
        contentType: false,

<!--        csrfmiddlewaretoken: '{{ csrf_token }}',-->
        success: function (data) {
            console.log(data);
        }
    });
    }
  } else {
    alert('Файл не найден');
  }
}

</script>

I get these files in django view:
def upload_private_chat(request):
    a = request.POST.get('image_message')
    a2 = request.POST.get('csrfmiddlewaretoken')
    print(a, a2)
    if request.method == 'POST':
        with open('jghghj.png', 'w') as file:
            os.chdir(r'/media') # X1
            file.write(request.POST.get('image_message'))
        # a = request.POST.get('image_message')
        # print(a)
    return HttpResponse("ok")

If a2 i.e. textual information, I get and write it without problems (although I don't need it), while on the output of photos (and on loading) output 'TypeError: write() argument must be str, not None'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gromyko21, 2020-10-30
@gromyko21

Another handler was needed (which simply saves the file, and gives the path to it in js).

def upload_private_chat(request):

    fs = FileSystemStorage(location='./media/message_image')

    myfile = request.FILES.get('image_message')
    print(myfile)
    filename = fs.save(myfile.name, myfile)
    uploaded_file_url = fs.url(filename)

    return HttpResponse( uploaded_file_url)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question