自学Python第二十二天- Django框架 AJAX、文件上传、POST 请求类型之间的转换、多APP开发、iframe、验证码、分页器、类视图、中间件、信号、日志、缓存
    		       		warning:
    		            这篇文章距离上次修改已过444天,其中的内容可能已经有所变动。
    		        
        		                
                
# views.py
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
 
@csrf_exempt
def upload_file(request):
    if request.method == 'POST':
        # 假设我们在HTML中有一个名为'myfile'的文件字段
        myfile = request.FILES['myfile']
        # 处理文件保存逻辑...
        # 返回JSON响应
        return JsonResponse({'status': 'success', 'message': '文件上传成功!'})
    else:
        return JsonResponse({'status': 'error', 'message': '请使用POST方法提交。'})
 
# urls.py
from django.urls import path
from .views import upload_file
 
urlpatterns = [
    path('upload/', upload_file, name='upload_file'),
]
 
# HTML中的JavaScript代码片段
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('upload-form').addEventListener('submit', function(event) {
        event.preventDefault(); // 阻止表单默认提交行为
        var formData = new FormData(this);
        fetch('/upload/', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => alert(data.message))
        .catch(error => alert('文件上传失败'));
    });
});这个示例展示了如何在Django视图中处理文件上传,并且使用AJAX进行异步上传,避免了页面刷新。同时,展示了如何使用fetchAPI进行POST请求,并处理其响应。注意,这里的代码片段只是一个简化的示例,实际应用中需要完善错误处理和文件上传的逻辑。
评论已关闭