angularjs + django 处理含文件的表单, 批量上传文件

xiaoxiao2021-02-27  272

参考: 出处 (angularjs 和 HTML 处理表单)

 出处 (接收到文件下载)

出处 (批量上传)

重点内容:

1.$http({***, data: $scope.yourData, upload: $scope.yourFile, ****}),

其中yourData用JSON.stringify($scope.yourData)处理一下POST给后台, django接收时,form_data = json.loads(request.POST['data']).

其中youFile不用处理直接发送到后台,django接收时,upload_file = request.FILES['upload'],因为form-data的POST形式,文件直接从FILES里读取了.

2.下载文件时,

django views.py:

@csrf_exempt def download_file(request, file_addr): def file_iterator(file_addr): with open(file_addr) as f: while True: c = f.read(512) if c: yield c else: break temp, filename = os.path.split(file_addr) response = StreamingHttpResponse(file_iterator(file_addr.encode('utf-8'))) response['Content-Type'] = 'application/octet-stream' response['Content-Disposition'] = 'attachment;filename="{0}"'.format(filename.encode('utf-8')) return response urls.py:

url(r'^download_file/(?P<file_addr>.+)/$',views.download_file,name='download_file'), angularjs:

$scope.download = function() { var fileAddr = ''; for (i in $scope.allData.inputs) { if ($scope.allData.inputs[i].type === 'FILE') { fileAddr = $scope.allData.inputs[i].result } } if (fileAddr !== '') { location.href = '/myproject/download_file/'+fileAddr+'/'; } else { alert('没有文件'); } }

转载请注明原文地址: https://www.6miu.com/read-8475.html

最新回复(0)