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?

2 Answers 2

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'})
  }
}), 
....
Sign up to request clarification or add additional context in comments.

7 Comments

where are you using JSON.parse()?
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?
is the file attribute a string or is it an actual file?
The html line for the file is this: <input type="file" files-model="newPost.image" required >
it seems to me then that you would have to instead do a <form></form> submit, or a file uploader control if you're using services. can't use AJAX to send a file directly. blog.teamtreehouse.com/uploading-files-ajax. if you're trying to send multipartform data, you can't send it as js obj
|
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'
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.