Django+vue implements folder upload, super simple version (pro-test effective)

I recently learned to upload and upload files in django. There is no upload and download of folders on the Internet at all. I found several, and reported a lot of errors. None of them can be used. ! ! The following method is what I have just used, and I will share it with you.

The front-end vue is very simple, the template part

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

Only two are needed, one inout selects the folder, and the other clicks the button to upload the file

The js part of the code is as follows:

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'}
          
     });

The above part of vue is all completed

Here is the django part, super simple

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')

Finished! ! I have made it!

Guess you like

Origin blog.csdn.net/qq_43644046/article/details/131101572