django获取服务器的文件路径,django上传文件夹获取路径名

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

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

后端获取:

request.POST.getlist('paths')

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

大致代码:

前端

点击测试

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

}

});

});

后端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">也行

Django中,处理用户通过HTML表单上传的文件通常涉及到两个关键步骤:HTML模板中设置表单,以及视图函数中接收并处理文件。以下是基本流程: 1. **HTML模板**: 使用`<input type="file">`标签让用户选择文件,并设置`name`属性以便于在服务器端识别。例如: ```html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file_upload" accept=".pdf"> <button type="submit">上传</button> </form> ``` `enctype="multipart/form-data"`属性用于支持文件上传。 2. **视图函数**: 在视图中,你需要使用`request.FILES`字典来获取上传的文件。如果文件上传成功,`file_upload`键对应的将是`UploadedFile`类型的对象,它包含了文件名、大小等信息以及一个打开文件流的方法。 ```python def upload_file(request): if request.method == 'POST': file = request.FILES['file_upload'] # 检查文件是否存在及是否接受的类型 if file and allowed_extensions(file.name): # 找到文件存储的位置,通常是 Django 的MEDIA_ROOT目录下 file_path = os.path.join(settings.MEDIA_ROOT, file.name) with open(file_path, 'wb') as destination: for chunk in file.chunks(): destination.write(chunk) return HttpResponse("文件已上传") else: return HttpResponse("无效或不接受的文件类型") ``` 然后你可以将文件保存到你希望的地方,如`settings.MEDIA_ROOT`指定的媒体文件。 3. **安全注意**: 验证文件类型是非常重要的,可以防止恶意上传。在上述代码中`allowed_extensions()`是一个示例函数,检查文件是否属于允许的文件类型列表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值