django上传文件夹获取路径名

2018-11-28  本文已影响0人  warmi_

不可能,它是InMemoryUploadedFile文件,就是个存内存的假文件。所以要从前端的js的formdata里添加一句相对路径参数:

fd.append("paths", files[i]['webkitRelativePath'])

后端获取:

request.POST.getlist('paths')

然后根据相对路径创文件夹,上传文件就好了

大致代码:
前端

<input type='file' webkitdirectory >  <button >点击测试</button>
<script>
    var files = [];
    $(document).ready(function(){
        $("input").change(function(){
            files = this.files;
        });
        $("button").click(function(){
            var fd = new FormData();
            for (var i = 0; i < files.length; i++) {

               fd.append("files", files[i]);
               fd.append("paths", files[i]['webkitRelativePath']);

            }
               console.log(files[2]['webkitRelativePath']);
            $.ajax({
                url: "api/project/upload",
                method: "POST",
                data: fd,
                contentType: false,
                processData: false,
                cache: false,
                success: function(data){
                    console.log(data);
                }
            });
        });
</script>

后端view.py

@csrf_exempt
def project_upload(request):

    if request.method == 'POST':

        dir=request.FILES
        dirlist=dir.getlist('files')
        pathlist=request.POST.getlist('paths')
        print(dir)
        if not dirlist:
            return HttpResponse( 'files not found')
        else:

            for file in dirlist:
                position = os.path.join(os.path.abspath(os.path.join(os.getcwd(),'projects')),'/'.join(pathlist[dirlist.index(file)].split('/')[:-1]))
                if not os.path.exists(position):
                    os.makedirs(position )
                storage = open(position+'/'+file.name, 'wb+')    
                for chunk in file.chunks():          
                    storage.write(chunk)
                storage.close()                 
            return HttpResponse( '1') 

另,上传文件夹不用form的enctype="multipart/form-data">也行

上一篇 下一篇

猜你喜欢

热点阅读