gpt4 book ai didi

python - 使用 Angular 和 Django 上传文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:01:14 25 4
gpt4 key购买 nike

所以,我遇到了一个找不到解决方案的问题。我正在使用 Django 开发一个应用程序,我的前端必须在 angular-js 中。现在我可以呈现表单并发布表单中的数据,但我不知道如何使用这些表单上传文件。

这是我的代码:

在 urls.py 中

url(r'^getter/$', TemplateView.as_view(template_name = "upload.html"))
url(r'^getter/test/', views.test, name = "thanks.html")

在 views.py 中

def test(request):
upload_form = uploadform(request.POST, request.FILES)
data = json.loads(request.body)
file_path = data.path

在表单中

select_file = forms.FileField(label = "Choose File")

在我的 Controller 中的 js 文件中

myapp.controller('abc', function ($scope, $http)
$scope.submit = function(){
var file = document.getElementById('id_select_file').value
var json = {file : string(file)}
$http.post('test/',json)
...success fn....
...error fn...

};});

现在的问题是如果在我看来如果我这样做

f = request.FILES['select_file']

我收到在 MultiValueDict 中找不到的错误“select_file”:{}

可能的问题是发送我的帖子请求的方式没有发送所有元数据....请帮助我解决这个问题我花了一整天寻找解决方案但无济于事。

PS:由于某些限制政策我不能使用Djangular 所以请给我不使用djangular 的解决方案。谢谢

编辑:**将文件属性应用于服务器正在接收的 json 也不起作用 **

最佳答案

我遇到了同样的问题。我找到了一个关于如何使用 Angular $http 将文件发送到 Django Forms 的有效解决方案。

指令

app.directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});

HTML

<form ng-submit="send()" enctype="multipart/form-data">
<input type="text" ng-model="producer.name" placeholder="Name">
<input type="file" files-input ng-model="producer.video">
</form>

Controller

$scope.send = function(){
var fd = new FormData();
fd.append('video', $scope.producer.video[0]);
fd.append("name", $scope.producer.name);

$http({
method: 'POST',
url: '/sendproducer/',
headers: {
'Content-Type': undefined
},
data: fd,
transformRequest: angular.identity
})
.then(function (response) {
console.log(response.data)
})
}

DJANGO View 表单

class ProducerView(View):

def dispatch(self, *args, **kwargs):
return super(ProducerView, self).dispatch(*args, **kwargs)

def post(self, request):
form = ProducerForm(data = request.POST, files = request.FILES or None)
if form.is_valid():
form.save()
return JsonResponse({"status": "success", "message": "Success"})
return JsonResponse({"status": "error", "message": form.errors})

关于python - 使用 Angular 和 Django 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com