Answer the question
In order to leave comments, you need to log in
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>
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")
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question