Multipart Form Upload Image and Json

不羁岁月 提交于 2019-11-30 20:27:21
Here is the code what i did in my project to upload image and data:- 
HTML PAGE :-
<form role="form" name="myForm" ng-submit="submitCuisine(myForm.$valid)" novalidate>
            <div class="form-group" ng-class="{ 'has-error' : myForm.name.$invalid && myForm.name.$touched }">
               <label for="name">Name</label>
               <input type="text" class="form-control" id="name"  name="name"
                  placeholder="Name of cuisine" ng-model="dataform.name" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.description.$invalid && myForm.description.$touched }">
               <label for="description">Description</label>
               <input type="text" class="form-control" id="description" name="description" 
                  placeholder="Description for cuisine" ng-model="dataform.description" required>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.category.$invalid && myForm.category.$touched }">
               <label for="description">Category</label>
                <select class="form-control" ng-model="dataform.category" id="category" name="category" required>
                   <option>Veg</option>
                   <option>Non-veg</option>
                 </select>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.subcategory.$invalid && myForm.subcategory.$touched }">
               <label for="description">Sub-Category</label>
                <select class="form-control" ng-model="dataform.subcategory" id="subcategory" name="subcategory" required>
                   <option>Main Course</option>
                   <option>Staters</option>
                 </select>
            </div>
            <div class="form-group" ng-class="{ 'has-error' : myForm.price.$invalid && myForm.price.$touched }">
               <label for="description">Price</label>
               <span class="fa fa-dollar"></span>
               <input type="number" class="form-control" id="price" name="price" 
                  placeholder="Price" ng-model="dataform.price" required>
            </div>  
            <div class="form-group">
               <label for="description">Image</label> 
               <input type="file"  file-input="files" name="file"/>
            </div>  
            <button class="btn btn-primary" type="submit" ng-disabled="myForm.$invalid"> Submit</button>
        </form>



Controller:-
$scope.submitCuisine=function(isvalid){
    if(isvalid){
        var fd=new FormData();
        angular.forEach($scope.files,function(file){
            fd.append('file',file);
        });

        fd.append('formdata',JSON.stringify($scope.dataform));

        $http.post('admin/managecuisineAdd',fd,{
            transformRequest:angular.identity,
            headers:{'Content-type':undefined}
        }).success(function(data){
            $scope.status=data;
            $scope.itemlist.push(data)
            $scope.message="New Dish Added Successfully"
        });
    }   
}

Directive :-
myApp.directive("fileInput",['$parse',function($parse){
    return{
        restrict:'A',
        link:function(scope,ele,attrs){
            ele.bind('change',function(){
                $parse(attrs.fileInput).
                assign(scope,ele[0].files)
                scope.$apply()
            });
        }
    }
}]);

Plunker:- http://plnkr.co/edit/yPNA0ij3Dn37tsI9w7Z2?p=preview check the post header in firebug you will find that it is showing image in encrypted form and data in the end of it.

Use formData as conteiner like say @squiroid

In html code

<form ng-submit="vm.uploadFile()">
      <input type="file" id="filePhoto" name="file">
      <button type="submit">Save</button>
</form>
{{vm.previewImage()}}

In my controller

vm.previewImage = previewImage;
function previewImage(){
        console.info("vm.file "+vm.file);
        var imageLoader = document.getElementById('filePhoto');
        console.info(imageLoader);
        imageLoader.addEventListener('change', handleImages, false);

        function handleImages(e) {
            console.info("entra handleImage");
            vm.file = e.target.files[0];
            console.info("archivo ");
            console.info(vm.file);
        }
}

vm.uploadFile = uploadFile;
function uploadFile() {
    return dataFactory.uploadFile(
        vm.file)
        .then(function successCallback(response) {
            console.info('uploadFile success');
            console.info(response);
        }, function errorCallback(response) {
            console.info('updauploadFileteUser fail');
            console.info(response);
        });
}

In DataFactory

function updateUser(token,file,username,email,lenguaje,colapsarMenu){
    var formData=new FormData();
    formData.append('file',file);
    //append more params if you want

    return $http
        .post('/uploadFile',
        formData,{
            transformRequest:angular.identity,
            headers: {
                //Optional token bearer 'Authorization': 'Bearer '+token,
                'Content-type':undefined
            }
        });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!