天天看点

在django中 使用 jq上传文件

使用jq上传文件的demo

本文章是用jq在基于python3 Django2.1 实现的简单上传文件的功能

第一次写文章,有哪里出问题了,请各位大佬多多教导!

1.创建django项目

在pycharm 左上角File >New Project > Django >选择环境(只要安装有的话一般默认就行【my_django_project1】是本次项目的名字)>Create

在django中 使用 jq上传文件

2.创建app

在底部打开pycharm 的命令行工具Terminal:输入python manage.py startapp mydemo2

3.配置url

1.在mydemo2 的app下创建urls.py,然后在my_django_project1的文件夹下导入这个urls.py

在django中 使用 jq上传文件

2.在mydemo2 的app下的urls中配置url链接及在view.py 中配置处理请求的视图函数

在django中 使用 jq上传文件
在django中 使用 jq上传文件

3.在命令行工具Terminal 中输入:python manage.py runserver 运行项目

在浏览器中输入链接查看效果okok

在django中 使用 jq上传文件

4.将view中的get的HttpResponse(“okoko”)换成render(request,‘mydemo2/index.html’,{})

index.html 是我事先在bootstrap 官网上复制的模板,在浏览器中输入链接查看效果

在django中 使用 jq上传文件
在django中 使用 jq上传文件

4.jq 上传文件

1.在index.html 中加入

<form id="mydemo2" enctype="multipart/form-data">
          <input type="file" name="upfile" id="upfile" value="">
          
        <button class="btn btn-success" onclick="func1">上传</button>
 </form>
           

当然要事先导入

<link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" target="_blank" rel="external nofollow" >
<script src="/static/js/jquery-1.12.4.js"></script>
           

效果图:

在django中 使用 jq上传文件

2.func1 ajax上传文件的代码

function func1(){
         var file=$("#upfile")[0].files[0]
         var formData=new FormData()
         formData.append('upfile',file)
         $.ajax({
             type:"post",
             url:'upfile/',
             data: formData,
             processData: false,
             contentType: false,
             success:function (data) {
                 console.log(data)
             },
             error:function (xhr) {
                 console.log(xhr)
             }
         })
     }
           

3.在mydemo2 的urls.py 中添加

re_path(r'^upfile/$',mydemo2.My_handle.as_view(),name="upfile"),
           

4.在mydemo2 中的view.py 中

class My_handle(View):
    def get(self,request):

        return render(request,'mydemo2/index.html',{})

    def post(self,request):
        BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        if request:
            file_object=request.FILES.get('upfile') #获取前端上传的文件
            print(file_object.name)
            #创建保存路径
            path=os.path.join(BASE_DIR,'mydemo2/db/{}'.format(file_object.name))
            path=path.replace('\\','/')
            if os.path.exists(path):
                #如果文件存在 就不处理。。
               return HttpResponse(" file already exists!")
            else:
                f=open(path,'wb+')
                #分段把文件写入到路径中
                for chunk in file_object.chunk():
                    f.write(chunk)
                f.close()
                return HttpResponse("file save ok!!")
           

最后就能在mydemo2 下的db文件夹下看见上传的文件了

在django中 使用 jq上传文件

还有很多细节处理不好,下次再改进!!!

仓库链接: https://gitee.com/htg_nice/my_django_demo19-4-3.git

继续阅读