1

I'm doing a simple blog with Angular + Django. I have a page when the user can create a new post, writing the title and the body. In addition, at the end, he can add a file.

This is the controller:

$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');
  }
};

This is the service where I call the server:

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

The problem is that if I try to add a new post, I get a 400 Error. In particular in the 'response' tab on 'Network' (Firefox) I have a red line that writes: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data. How can I do?

panagulis72
  • 2,129
  • 6
  • 31
  • 71

2 Answers2

0

Before you send the parameters, use JSON.stringify().

.....
addPost: $resource('my_url', {
}, {
  add: {
    method: 'POST',
    headers: { 'Content-Type': 'multipart/form-data' },
    params: JSON.stringify({title:'title', text:'text', file: 'file'})
  }
}), 
....
A.J.
  • 393
  • 1
  • 8
  • where are you using JSON.parse()? – A.J. Apr 28 '16 at 13:29
  • nowhere: in the question I pasted the code I use! Maybe it take the word 'file' as text and doesn't take the entire file? – panagulis72 Apr 28 '16 at 13:37
  • is the file attribute a string or is it an actual file? – A.J. Apr 28 '16 at 13:43
  • The html line for the file is this: – panagulis72 Apr 28 '16 at 13:44
  • it seems to me then that you would have to instead do a
    submit, or a file uploader control if you're using services. can't use AJAX to send a file directly. http://blog.teamtreehouse.com/uploading-files-ajax. if you're trying to send multipartform data, you can't send it as js obj
    – A.J. Apr 28 '16 at 13:48
  • It already is a form! With two input text and one input file... So what I should do? I have no problem to change the code structure – panagulis72 Apr 28 '16 at 14:00
  • sorry about that. i thought this question was something else. maybe this will help you: http://stackoverflow.com/questions/21115771/angularjs-upload-files-using-resource-solution – A.J. Apr 28 '16 at 14:03
0

You can use $upload to upload file

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