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

参考: 出处 (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('没有文件');
            }

        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值