[英]Upload file with plain AJAX/JS and Django
this is my popup form 这是我的弹出表格
<div class="popup media-upload-form">
<div class="border cf">
<div class="close">X</div>
</div>
<form class="cf" action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<!-- {{ form.as_p }} this is what i use, just putting plain html to show you all inputs -->
<p>
<label for="id_audio">Audio:</label>
<input type="file" name="audio" required id="id_audio" />
</p>
<input class="button" type="submit" value="Upload" />
</form>
</div>
this how i used to do it without ajax 这是我过去没有ajax的方式
def upload_media(request):
if request.method == 'POST':
form = forms.MediaForm(request.POST, request.FILES)
if form.is_valid():
media_file = form.cleaned_data['audio']
media = models.PlayerMedia()
media.user = request.user
media.title = str(media_file)
media.description = 'good song'
media.media = media_file
media.save()
return HttpResponse('done')
file is coming from requets.FILES['filename'] and that's the problem, i don't know how to send file from js to django view. 文件来自requets.FILES ['filename'],这就是问题,我不知道如何从js发送文件到django视图。 JQuery has some plugins but i want to do it without any libraries.
jQuery有一些插件,但我想没有任何库。
this is what i have so far 这就是我到目前为止
var uploadForm = document.querySelector('.media-upload-form form');
var fileInput = document.querySelector('.media-upload-form form #id_audio');
uploadForm.onsubmit = function(e) {
e.preventDefault();
var fileToSend = fileInput.value; // this is not it
}
so how do i get reference to selected file and send it with ajax to Django for processing? 那么我如何获得对所选文件的引用,并将其与Ajax一起发送给Django进行处理?
I got it! 我知道了!
Turns out, i needed a FormData object to send files, so i get file out of input with files property, and just created FormField put in file with append function and send as regular data, here's what it looks like 事实证明,我需要一个FormData对象来发送文件,所以我通过使用files属性从输入中获取文件,并且刚刚创建了具有append函数的FormField放在文件中并作为常规数据发送,如下所示
var mediaFile = fileInput.files[0];
var formData = new FormData();
formData.append('media', mediaFile);
request.send(formData); // done
and then receive it from Django view with request.FILES 然后从Django视图中使用request.FILES接收它
def upload_media(request):
if request.method == 'POST':
media_file = request.FILES['media']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.