Django+Bootstrap实现页面文件上传(使用Krajee插件)

首先附上Krajee的文件上传插件官网

安装插件

参考官网的安装方法我选择命令行安装

 bower install bootstrap-fileinput

这个时候可能会提醒bower无法识别,那么就要涉及到bower的安装了

//我的电脑没有npm,首先我安装了npm
brew install npm
//如果没有安装brew,自己取搜索安装吧
//然后安装bower
npm install bower
//开始配置
vim ~/.bash_profile
//插入
export BOWER=your address/bower/bin
//更新配置
source ./bash_profile
//测试是否安装完成
bower -v
//可以回头执行第一个代码了

开始页面编写

首先html导入






















< script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.0.1/themes/fas/theme.min.js">


他有两种方式来上传文件ajax和form
我使用的是ajax
进入官方给的demo网址选择合适的样式,直接就可以复制官网的demo代码修改一下放在自己的html中

后端接收文件

在views.py的编写接收文件

from django.views.decorators.csrf import csrf_exempt
#这个千万不要忘记导入,否则会没办法上传因为没有权限
@csrf_exempt
def uploadData(request):
    #form = UploadFileForm(request.POST, request.FILES)
    #在html页面中上传file处的name我设置得是upload
    file=request.FILES.get('upload')
    f=open(os.path.join('uploadData',file.name),'wb+')
    for chunk in file.chunks():
        f.write(chunk)
    j={'filebatchuploadsuccess':'成功'}
    return HttpResponse(json.dumps(j), content_type="application/json")
file=request.FILE

这样就可以成功的上传了
但是有一件事情很重要不要忘记
一定要返回一个json数据,哪怕是返回空的也要返回不然页面会报错

官网对于返回值的说明
You MUST send a valid JSON response from your server, else the upload process will fail. Even if you do not encounter any error, you must at least send an empty JSON object {} from your server.
To trap and display a validation error, your JSON response data must include the error key, whose value will be the error HTML markup to display. In addition, you must typically also send the errorkeys for synchronous mode to identify the keys for files which faced errors. This is to be setup as mentioned above.
You can also send in additional keys or data with your JSON response, for you to process them for advanced cases using events like filebatchuploadsuccess.

你可能感兴趣的:(Django学习)