Search code examples
angularjsfile-upload

How to send correct content type for each part of form data (in case of FormData with file upload and other form fields) in AngularJS?


As shown in an accepted solution here; I am able to send multipart formdata with file and other form fields. However, for other form fields, the content type is missing in the request,the multipart form data looks something like this:

------WebKitFormBoundaryx2K3e9RYOyHECg8E
Content-Disposition: form-data; name="containerId"

12345
------WebKitFormBoundaryx2K3e9RYOyHECg8E
Content-Disposition: form-data; name="fileName"

てすと.qml
------WebKitFormBoundaryx2K3e9RYOyHECg8E
Content-Disposition: form-data; name="filePathInput"; filename="てすと.qml"
Content-Type: application/octet-stream

...... all file file contents

As you can see, content type is passed only for the file content, not for the fileName and containerId form data

For other form fields, the content type is missing in the request, because of which, if I send a multibyte character as form data, I am unable to read that in server (because server tries to read it in ISO encoding and input becomes garbled).

What should I do to send content type with each part in multipart form data using AngularJS?

Just for example, the current code looks like:

angular.directive('fileUpload', function($parse,$http) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                // some code....
                var onSubmit;
                if (window.FormData) {
                    onSubmit = function(e) {
                        var formData = new FormData(e.target);
                        if (attrs.formData) {
                            angular.forEach($parse(attrs.formData)(scope), function(value, key) {
                                formData.append(key, value);
                            });
                        }
                        $http.post('some_url',formData,headers: {headers:
                            {'Content-Type': undefined},
                            transformRequest: angular.identity
                        }).success(function(response) {
                            // do some stuff
                        });
// some more code....
}}}}});

Solution

  • I found the answer... with lots of thinking over it, and sinking my head on lots of such stuff related to file upload in anglarjs, the answer is just to wrap all the form data in blob as :

    replace --> formData.append(key, value); with --> formData.append(key, new Blob([value]));

    and all the form data are now sent with content type as blob, the server automatically detects the correct data type inside the blob.