如何在POST上使用Ajax上传文件?

编程入门 行业动态 更新时间:2024-10-22 19:27:34
本文介绍了如何在POST上使用Ajax上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道,关于这个主题的话题并非没有,但请耐心等待.我想使用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上传文件?

本文发布于:2023-10-11 22:45:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1483052.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上传文件   如何在   POST   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!