django+vue实现文件夹上传,超简单版本(亲测有效)

最近学django的文件上下传,网上的文件夹上下传压根没有,找了好几个,报错一大堆,没有一个能用,花里胡哨,可气!!!下面这个方法是我刚刚用过的,分享给大家。

前端vue非常简单,template部分

<input type="file" id="twos" webkitdirectory/>
<el-button type="primary" @click="sumfolder">文件夹提交</el-button>

只需要两个,一个inout选取文件夹,另一个点击按钮,上传文件

js部分代码如下:

async sumfolder() {
      //拿到元素节点
      let twos=document.getElementById('twos')
      //读取dom节点图片
      const file = twos.files
      //声明一个对象,传递图片用
      let obj=new FormData()
       //循环将图片读入formdata,并且给个不同的'flies'+i,不然会被覆盖
      for(let i=0;i<file.length;i++){
        console.log(file[i])
        obj.append('flies'+i,file[i])
      }
      
      //也可以传递一些其他表单信息  obj.append('admin_id','admin_id')【可选项】
      //我这里axios封装了成了this.$http,你们也可以直接替换this.$http成为axios.post({})效果一样
      const { data: res } = await this.$http({
          url:"http://127.0.0.1:8000/rotate/",
          method: "POST",
          data:obj,
          headers:{'content-type':'application/x-www-form-urlencoded'}
          
     });

以上部分vue就全部完成了

下面是django部分,超级简单

import os
from pathlib import Path
from django.shortcuts import HttpResponse,render

#旋转操作
def rotate(request):
    BASE_DIR = Path(__file__).resolve().parent.parent
    if request.method == 'POST':
        print(request.FILES)
        if request.FILES:
            for i in request.FILES:
                myFile = request.FILES[ i ]
                if myFile:
                    dir = os.path.join(os.path.join(BASE_DIR, 'img\\static'), 'upload') #这里自己配好要保存的路径
                    destination = open(os.path.join(dir, myFile.name),
                                       'wb+')
                    for chunk in myFile.chunks():
                        destination.write(chunk)
                    destination.close()
    return HttpResponse('ok')

完工!!我已经成功了!

猜你喜欢

转载自blog.csdn.net/qq_43644046/article/details/131101572