文件上传
方式一、使用django
中的表单上传的方式
1、在
models.py
中定义字段class UserProfileModel(AbstractUser): """ 创建一个用户的模型 """ nick_name = models.CharField(max_length=50, verbose_name='昵称', null=False, default='') .... # 定义需要上传的头像字段 image = models.ImageField(upload_to='images/users/%Y/%m', default='images/default.jepg', verbose_name='头像') ...
2、在
forms.py
中定义class UploadImageForm(forms.ModelForm): """ 定义用户上传图片的form """ class Meta: model = UserProfileModel fields = ['image']
3、书写视图层
... from django.contrib.auth.mixins import LoginRequiredMixin class UploadImageView(LoginRequiredMixin, View): """ 用户上传图像视图,LoginRequiredMixin表示需要先登录 """ def post(self, request, *args, **kwargs): image_form = UploadImageForm(request.POST, request.FILES) if image_form.is_valid(): image = image_form.cleaned_data['image'] request.user.image = image request.user.save() return HttpResponse('上传成功') return HttpResponse('选择文件')
4、配置
url
地址5、前端静态页面的书写(注意这个地方
<font color="#f00">enctype="multipart/form-data"</font>
)<form class="clearfix" enctype="multipart/form-data" method="post" action="url"> <label class="changearea" for="avatarUp"> <span id="avatardiv" class="pic"> <img width="100" height="100" src=""/> </span> <span class="fl upload-inp-box" style="margin-left:70px;"> <span class="button btn-green btn-w100" id="jsAvatarBtn">修改头像</span> <input type="file" name="image" id="avatarUp" class="js-img-up"/> </span> </label> </form>
6、补充说明(如果是要上传文件
models.py
中修改)file = models.FileField(upload_to='file/%Y/%m', verbose_name='上传文件')
方式二、使用ajax
提交的方式
1、创建一个简单的页面
<div class="container"> <div class="form-group"> <label for="exampleInputFile">附件上传</label> <input type="file" name="file" id="file_upload"> <button type="button" class="btn btn-default" id="btn">开始上传附件</button> </div> </div>
2、视图类的书写
import os import time from django.shortcuts import render from django.http import HttpResponse from django.views import View class UploadTestView(View): def get(self, request, *args, **kwargs): return render(request, 'upload.html', locals()) def post(self, request, *args, **kwargs): file_obj = request.FILES.get('file') if file_obj: print('file--obj', file_obj) accessory_dir = 'media' if not os.path.isdir(accessory_dir): os.mkdir(accessory_dir) upload_file = "%s/%s" % (accessory_dir, file_obj.name) with open(upload_file, 'wb') as new_file: for chunk in file_obj.chunks(): new_file.write(chunk) order_id = time.strftime("%Y%m%d%H%M%S", time.localtime()) return HttpResponse(order_id)
3、使用
jquery
来提交$(function () { $('#btn').on('click', function () { var form_data = new FormData(); var file_info = $('#file_upload')[0].files[0]; form_data.append('file', file_info); // 提交ajax的请求 $.ajax({ url: "/operation/upload/", type: 'POST', data: form_data, processData: false, // tell jquery not to process the data contentType: false, // tell jquery not to set contentType success: function (data) { console.log(data) } }); }) })
4、注意我是注释了
csrf
的校验提交的