Django Rest Framework AngularJs Upload Image
Bonjour,
J'effectue une Api avec Django Rest Framework, j'utilise AngularJs pour le front et fait donc des requêtes get, post, etc à l'Api.
Ici je souhaite faire une requête post pour envoyer une image or je me retrouve avec l'erreur
Code:
image: ["The submitted data was not a file. Check the encoding type on the form."]
J'utilise ng-file-upload pour upload l'image.
Concernant mon code:
- Models.py
Code:
1 2 3
| class Image(models.Model):
image = models.ImageField(upload_to="articles")
article = models.ForeignKey(Article) |
- Serializers.py
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
| class ImageSerializer(serializers.ModelSerializer):
class Meta:
#article = ArticleSerializer(read_only=True, required=False)
image = serializers.ImageField(use_url=True, allow_empty_file=True)
model = Image
fields = ('id', 'image', 'article')
read_only_fields = ('id', )
#def get_validation_exclusions(self, *args, **kwargs):
# exclusions = super(ImageSerializer, self).get_validation_exclusion()
# return exclusions + ['article'] |
- Le controlleur
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
(function () {
'use strict';
angular
.module(nameProject + '.article.post.controller')
.controller('ArticlePostController', ArticlePostController);
ArticlePostController.$inject = ["$scope", "Articles", "Upload", "$timeout"];
function ArticlePostController($scope, Articles, Upload, $timeout) {
var vm = this;
vm.postArticle = postArticle;
//Debut
$scope.$watch('files', function () {
$scope.upload($scope.files);
console.debug("files = ", $scope.files);
//console.debug("upload = ", $scope.upload);
});
$scope.upload = function (files) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
console.debug("file = ", file, "type = ", file.type);
Upload.upload({
url: '/api/v1/images/',
fields: {
'idArticle': 1,
'article': 1,
'image': file
},
file: file,
image:file
}).progress(function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
$scope.log = 'progress: ' + progressPercentage + '% ' +
evt.config.file.name + '\n' + $scope.log
}).success(function (data, status, headers, config) {
$timeout(function () {
console.log("data === ", data.result);
$scope.log = 'file: ' + config.file.name + ', Response: ' + JSON.stringify(data) + '\n' + $scope.log;
/*
Articles.postImage(JSON.stringify(data) , 1);
*/
});
});
}
}
};
//Fin
}
})(); |
Ca fait un bon moment que je cherche mais je ne vois pas comment résoudre le problème