一、依赖
- 前端
前端插件地址 http://fex.baidu.com/webuploader/
- 后端
django2.2
二、这里只贴出核心代码
前端
Title
选择文件
开始上传
后端:
路由
path('files/upload/', views.fileupload,name='图片分片上传'),path('upload/complete/', views.fileMerge,name='上传成功合并'),
视图:
@csrf_exemptdef fileupload(request): if request.method == 'POST': upload_file = request.FILES.get('file') task = request.POST.get('task_id') # 获取文件唯一标识符 chunk = request.POST.get('chunk', 0) # 获取该分片在所有分片中的序号 filename = '%s%s' % (task, chunk) # 构成该分片唯一标识符 print("filename=",filename) default_storage.save('./upload/%s' % filename,ContentFile(upload_file.read())) # 保存分片到本地 return render_to_response('upload.html',locals())@csrf_exemptdef fileMerge(request): print(request.GET) task = request.GET.get('task_id') ext = request.GET.get('filename', '') upload_type = request.GET.get('type') if len(ext) == 0 and upload_type: ext = upload_type.split('/')[1] ext = '' if len(ext) == 0 else '.%s' % ext # 构建文件后缀名 chunk = 0 with open('./upload/%s%s' % (task, ext), 'wb') as target_file: # 创建新文件 while True: try: filename = './upload/%s%d' % (task, chunk) source_file = open(filename, 'rb') # 按序打开每个分片 target_file.write(source_file.read()) # 读取分片内容写入新文件 source_file.close() except IOError: break chunk += 1 os.remove(filename) # 删除该分片,节约空间 return render_to_response('upload.html',locals())
三、效果图