【问题标题】:Send file with Angular and Django使用 Angular 和 Django 发送文件
【发布时间】:2016-08-23 06:39:41
【问题描述】:

我正在用 Angular + Django 写一个简单的博客。当用户可以创建新帖子,写标题和正文时,我有一个页面。另外,最后,他可以添加一个文件。

这是控制器:

$scope.newPost = {};

$scope.addPost = function(){
  if ($scope.newPost){
    PostListSrv.addPost.add($scope.newPost, function(data) {
        if (data) {
          console.log('success');
        }
      }, function(error) {
        if (error) {
          console.log('error');
        }
      }
    );
  } else {

          console.log('Error');
  }
};

这是我调用服务器的服务:

   .....
  addPost: $resource('my_url', {
  }, {
    add: {
      method: 'POST',
      headers: { 'Content-Type': 'multipart/form-data' },
      params:{title:'title', text:'text', file: 'file'}
    }
  }), 
  ....

问题是,如果我尝试添加新帖子,我会收到 400 错误。特别是在“网络”(Firefox)上的“响应”选项卡中,我有一条红线写着:SyntaxError:JSON.parse:JSON 数据的第 1 行第 1 列的数据意外结束。我该怎么办?

【问题讨论】:

    标签: javascript angularjs django rest post


    【解决方案1】:

    您可以使用$upload上传文件

    $upload.upload({
        url: 'servicesUrl/',
        file: fileToBeUpload,
        data: {'title': title},
        method: 'POST',
        withCredentials: false,
        contentType:'application/json',
        dataType:'json'
    });
    

    【讨论】:

      【解决方案2】:

      在发送参数之前,请使用JSON.stringify()

      .....
      addPost: $resource('my_url', {
      }, {
        add: {
          method: 'POST',
          headers: { 'Content-Type': 'multipart/form-data' },
          params: JSON.stringify({title:'title', text:'text', file: 'file'})
        }
      }), 
      ....
      

      【讨论】:

      • 你在哪里使用 JSON.parse()?
      • 无处:在问题中我粘贴了我使用的代码!也许它把“文件”这个词作为文本而不是整个文件?
      • 文件属性是字符串还是实际文件?
      • 文件的 html 行是这样的:
      • 在我看来,如果您正在使用服务,您将不得不改为进行
        提交或文件上传控制。不能使用 AJAX 直接发送文件。 blog.teamtreehouse.com/uploading-files-ajax。如果您尝试发送多部分数据,则不能将其作为 js obj 发送
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 2023-03-19
      • 2014-10-02
      • 2018-07-14
      • 1970-01-01
      • 2018-07-20
      相关资源
      最近更新 更多