Copy file to server using angular

I can't believe it's that hard. If you are using nodejs and standard html, I can transfer the file by doing:

index.html

<form id       =  "uploadForm"
     enctype   =  "multipart/form-data"
     action    =  "/api/photo"
     method    =  "post"
>
<input type="file" name="userPhoto" />
<input type="text" placeholder="keywords" name="keywords" />
<input type="submit" value="Upload Image" name="submit">
</form>

      

and on server.js

var express=require("express");
var multer  = require('multer');
var app=express();
var done=false;


app.use(express.static(__dirname + '/')); 

/*Configure the multer.*/
app.use(multer({ dest: './uploads/',
 rename: function (fieldname, filename) {
    return filename+Date.now();
  },
onFileUploadStart: function (file) {
  console.log(file.originalname + ' is starting ...')
},
onFileUploadComplete: function (file) {
  console.log(file.fieldname + ' uploaded to  ' + file.path)
  done=true;
}
}));


/*Handling routes.*/
app.get('/',function(req,res){
      res.sendfile("index.html");
});

app.post('/api/photo',function(req,res){
  if(done==true){
    res.end("File uploaded.");
  }
});

/*Run the server.*/
app.listen(3000,function(){
    console.log("Working on port 3000");
});

      

This way, any uploaded image is copied to the uploads folder. Now I want to use angular for various reasons. As it turns out, I need a directive. Why, I don't understand (but that 's another question ). Since I am using multer, I need data of type "multipart / form-data". This is my index.html:

</<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.0-rc.1/angular.min.js"></script>
</head>

<body ng-app="formExample">
<div ng-controller="ExampleController">

    <form ng-submit="examplePost()" role="form" >
        <input type="file" bind-file="" ng-model="file" />
        <input type="text" ng-model="keywords" placeholder="keywords"/>
        <input type="submit" ng-onclick="submit" value="Upload Image" >
    </form>

</div>

<script>
  angular.module('formExample', [])
    .controller('ExampleController', ['$scope', '$http', function($scope,$http) {
        $scope.master = {};

        $scope.examplePost = function() {

        $http({
            method: 'POST',
            url: '/upload-file',
            headers: {
                'Content-Type': 'multipart/form-data'
            },
            data: {
                upload: $scope.file
            },
            transformRequest: function (data, headersGetter) {
                var formData = new FormData();
                angular.forEach(data, function (value, key) {
                    formData.append(key, value);
                });

                return formData;
            }
        })
        .success(function (data) {

        })
        .error(function (data, status) {

        });

        };


    }])
    .directive('bindFile', [function () {
        return {
            require: "ngModel",
            restrict: 'A',
            link: function ($scope, el, attrs, ngModel) {
                el.bind('change', function (event) {
                    ngModel.$setViewValue(event.target.files[0]);
                    $scope.$apply();
                });

                $scope.$watch(function () {
                    return ngModel.$viewValue;
                }, function (value) {
                    if (!value) {
                        el.val("");
                    }
                });
            }
        };
    }]);
</script>

</body>
</html>

      

and I get a lovely 500 response: Error: Multipart: Border not found. Now I don't want to use external modules. I could, but actually I have to write a lot of code and send a lot of files plus some data, so I want to fully understand what is going on before choosing an external module (or writing it).

How to solve the error "Border not found" and what does it mean?

+3


source to share


1 answer


As for the "border", wikipedia pretty much explains it: http://en.wikipedia.org/wiki/MIME#Multipart_messages



A multi-user MIME message contains a border in the "Content-Type:" header; this border, which should not occur in any of the parts, is located between the parts, as well as at the beginning and end of the body of the message, as follows:

MIME-Version: 1.0
Content-Type: multipart/mixed; boundary=frontier

This is a message with multiple parts in MIME format.
--frontier
Content-Type: text/plain

This is the body of the message.
--frontier
Content-Type: application/octet-stream
Content-Transfer-Encoding: base64

PGh0bWw+CiAgPGhlYWQ+CiAgPC9oZWFkPgogIDxib2R5PgogICAgPHA+VGhpcyBpcyB0aGUg
Ym9keSBvZiB0aGUgbWVzc2FnZS48L3A+CiAgPC9ib2R5Pgo8L2h0bWw+Cg==
--frontier--

      

+2


source







All Articles