前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="/static/jquery-3.2.1.min.js"></script> <script src="/static/jquery.cookie.js"></script> </head> <body> <h1>文件上传页面</h1> <form action="/upload/" method="post" enctype="multipart/form-data"> {% csrf_token %} <p>用户名:<input type="text" name="username"></p> <p>文件:<input type="file" name="file"></p> <input type="submit" value="提交"><span>{{ successful }}</span> </form> </body> </html>
后端处理:
def upload(request): if request.method == "GET": return render(request,"upload.html") else: file_obj = request.FILES.get("file") with open(file_obj.name,"wb") as f: for line in file_obj: f.write(line) successful = "上传成功" return render(request,"upload.html",locals())
效果图:
简单的上传操作会让页面刷新,还有利用ajax无刷新技术上传的方式↓
时间: 2024-10-28 10:14:42