我知道,关于这个主题的话题并非没有,但请耐心等待.我想使用Ajax或等效文件将文件上传到服务器.
I know, the topics aren't missing on this subject but bear with me. I'd like to upload a file to the server using Ajax or an equivalent.
# html <form method="post" id="Form" enctype="multipart/form-data"> {% csrf_token %} # django security <input id="image_file" type="file" name="image_file"> <input type="submit" value="submit"> </form># javascript $(document).on('submit', '#Form', function(e){ e.preventDefault(); var form_data = new FormData(); form_data.append('file', $('#image_file').get(0).files); $.ajax({ type:'POST', url:'my_url', processData: false, contentType: false, data:{ logo:form_data, csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), # django security }, }); });
# views.py (server side) def myFunction(request): if request.method == 'POST': image_file = request.FILES ... ...
我猜我配置ajax函数的方式存在问题,因为在调试模式下,除logo之外的所有数据都返回.
I guess there's an issue with the way I configured the ajax function since on debug mode, every data are returned except the logo.
我做错了什么吗?
推荐答案回想一下,较早的答案不切实际,不建议这样做. asnyc: false暂停整个Javascript以仅上传文件,您可能在上传过程中触发了其他功能.
Looking back, the older answer is unpractical and not recommended. asnyc: false pauses the entire Javascript to simply upload a file, you are likely firing other functions during the upload.
如果您仅将JQuery用于ajax,那么我建议使用axios:
If you are using JQuery solely for the use of ajax, then I recommand using axios:
const axios = require('axios'); var formData = new FormData(); formData.append('imageFile', document.querySelector('#image_file').files[0]); axios({ method: 'post', url: 'your_url', data: formData, headers: { "X-CSRFToken": CSRF_TOKEN, # django security "content-type": "multipart/form-data" } }).then(function (response) { # success });Axios 文档
jQuery/Ajax答案:
var formData = new FormData(); formData.append('imageFile', $('#image_file')[0].files[0]); formData.append('csrfmiddlewaretoken', CSRF_TOKEN); # django security $.ajax({ url : 'your_url', type : 'POST', data : formData, processData: false, contentType: false, success : function(data) { # success } });Jquery/Ajax 文档
更多推荐
如何在POST上使用Ajax上传文件?
发布评论