【问题标题】:Upload File using Angular and Django使用 Angular 和 Django 上传文件
【发布时间】:2023-03-19 07:23:02
【问题描述】:

所以,我有一个问题,我找不到解决方案。我正在使用 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

在forms.py中

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

在我的控制器内的 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 也不起作用**

【问题讨论】:

  • 不知道 Django,但是你的 json 使用 file 并且你的视图引用 select_file 这是正确的吗?
  • @craigb 是的,刚刚编辑了我的问题。当我使用角度时,基本上没有 od django 的文件方法或函数起作用

标签: python django angularjs django-forms django-uploads


【解决方案1】:

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

指令

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>

控制器

$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 视图表格

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

【讨论】:

    【解决方案2】:

    使用下面的 sn-p 以便您可以将常用数据与文件数据一起从 angular 发送到 django。

    $scope.submit = function(){
        var fd = new FormData();
        datas = $("#FormId").serializeArray();
        // send other data in the form
        for( var i = 0; i < datas.length; i++ ) {
             fd.append(datas[i].name, datas[i].value);
            };
        // append file to FormData
        fd.append("select_file", $("#id_select_file")[0].files[0])
        // for sending manual values
        fd.append("type", "edit");
        url = "getter/test/",
        $http.post(url, fd, {
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
        }).
        error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
            });
    };
    

    现在您将在 django 视图中获得request.FILES 下的select_filerequest.POST 内的其他数据。

    【讨论】:

    • 我尝试了上面的 sn-p,它对我来说工作正常。我不知道为什么它被否决了。如果你能指出这个问题,那就太好了。谢谢!
    【解决方案3】:

    早期帖子与正确的 Angular 功能的组合。

    (function(app){
       app.controller("Name_of_Controller", function($scope, $http){
          $scope.submit = function(){
             var fd = new FormData();
             datas = $("#formID").serializeArray();
             for( var i = 0; i < datas.length; i++ ) {
                fd.append(datas[i].name, datas[i].value);
             };
            fd.append("selected_file", $("#file_id")[0].files[0])
            fd.append("type", "edit");
            url = "/results/",
            $http.post(url, fd, {
                headers: {'Content-Type': undefined },
                transformRequest: angular.identity
            }).then(function (response) {
                console.log(response.data)
            }).catch(function (err) {});;
        };
    });
    })(App_name);
    

    【讨论】:

      【解决方案4】:

      我强烈建议使用第三方插件,例如ngUploadfileUploader 来实现这一点。您在客户端上执行的操作看起来不正确。

      另请参阅this SO thread on angularjs file uploads

      【讨论】:

      • 有没有办法在使用 Angular 发布数据的同时使用 django 的文件上传功能? Django文件上传简单干净...
      猜你喜欢
      • 2017-07-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-12
      • 1970-01-01
      • 1970-01-01
      • 2020-11-28
      • 2017-11-02
      • 1970-01-01
      相关资源
      最近更新 更多