Upload multipart form data with filename in Request Payload Upload multipart form data with filename in Request Payload angularjs angularjs

Upload multipart form data with filename in Request Payload


You can use something along the line of:

<input type="file" name="file" onchange="uploadFile(this.files)"/>

And in your code:

$scope.uploadFile = function(files) {    var fd = new FormData();    //Take the first selected file    fd.append("file", files[0]);    var uploadUrl = ApiUrlFull + 'Job/Item?smartTermId=0&name=aaa1&quantity=1&ApiKey=ABC';    $http.post(uploadUrl, fd, {        withCredentials: true,        headers: {'Content-Type': undefined },        transformRequest: angular.identity    }).success( ...all right!... ).error( ..damn!... );};


My need was a follows.

  • In the form there is a default picture.
  • Clicking the picture opens a file select window.
  • When the user selects a file, it is uploaded right away to the server.
  • As soon as I get a response that the file is valid display the picture to the user instead of the default picture, and add a remove button next to it.
  • If the user clicks on an existing picture, the file select window reopens.

I tried to use a few code snippets on github that didn't solve the problem, but guided me in the right way, And what I ended up doing is as so:

Directive

angular.module("App").directive('fileModel', function ($parse) {    return {        restrict: 'A',        link: function (scope, element, attrs) {            scope.files = {};            var model = $parse(attrs.fileModel);            var modelSetter = model.assign;            // I wanted it to upload on select of file, and display to the user.            element.bind('change', function () {                scope.$apply(function () {                    modelSetter(scope, element[0].files[0]);                });                // The function in the controller that uploads the file.                scope.uploadFile();            });        }    };});

Html

<div class="form-group form-md-line-input">    <!-- A remove button after file has been selected -->    <span class="icon-close pull-right"          ng-if="settings.profile_picture"          ng-click="settings.profile_picture = null"></span>    <!-- Show the picture on the scope or a default picture -->    <label for="file-pic">        <img ng-src="{{ settings.profile_picture || DefaultPic }}"             class="clickable" width="100%">    </label>    <!-- The actual form field for the file -->    <input id="file-pic" type="file" file-model="files.pic" style="display: none;" /></div>

Controller

$scope.DefaultPic = '/default.png';$scope.uploadFile = function (event) {        var filename = 'myPic';        var file = $scope.files.pic;        var uploadUrl = "/fileUpload";        file('upfile.php', file, filename).then(function (newfile) {             $scope.settings.profile_picture = newfile.Results;            $scope.files = {};        });};function file(q, file, fileName) {    var fd = new FormData();    fd.append('fileToUpload', file);    fd.append('fn', fileName);    fd.append('submit', 'ok');    return $http.post(serviceBase + q, fd, {        transformRequest: angular.identity,        headers: { 'Content-Type': undefined }    }).then(function (results) {        return results.data;    });}

Hope it helps.

P.S. A lot of code was striped from this example, if you need clarification just comment.