Django 文件上传2022-07-28 18:11:28form表单上传文件 {% csrf_token %} 用户名:<input type="text" name="username" > 头像:<input type="file" name="avatar" multiple> <input type="submit"> </form> ajax上传文件 用户名:<input type="text" name="username" id="username"> 头像:<input type="file" name="avatar" id="avatar"> <button id="ajax_btn">上传</button> $(‘#ajax_btn‘).click(function () { var uname = $(‘#username‘).val(); var file_obj = $(‘#avatar‘)[0].files[0]; var formdata = new FormData(); formdata.append(‘username‘,uname); formdata.append(‘csrfmiddlewaretoken‘,‘{{ csrf_token }}‘); formdata.append(‘avatar‘,file_obj); $.ajax({ url:‘/login/‘, type:‘post‘, data:formdata, processData: false , // 不处理数据 contentType: false, // 不设置内容类型 success:function (res) { console.log(res); } }) }) 视图代码 def login(request): if request.method == ‘GET‘: return render(request, ‘login.html‘) else: # print(request.POST) # print(request.FILES) file_obj = request.FILES.get(‘avatar‘) print(file_obj) // JS语言.md <class ‘django.core.files.uploadedfile.InMemoryUploadedFile‘> name = file_obj.name print(name) // JS语言.md <class ‘str‘> # with open(fr‘C:\Users\oldboy\Desktop\Pointofix\{name}‘, ‘wb‘) as f: print(type(file_obj)) with open(name, ‘wb‘) as f: # 方式1 # for i in file_obj: # \r\n # 方式2 # for i in file_obj.chunks(): # \r\n for i in file_obj.chunks(): # \r\n 读取65536B f.write(i) return HttpResponse(‘ok‘) Django 文件上传上一篇:实验 4:Open vSwitch 实验——Mininet 中使用 OVS 命令下一篇:web项目的建立(idea版本)