Search code examples
angularjsng-file-upload

ng-model gives null for extension less files in angular js


I want to upload extension less file with the below snippet.

<button id="profileImage" ngf-select ng-model="imageFile" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-change="clearImageErrorMsgs()">Change Photo</button>

After i clicked on this "Change Photo" and select an extension less photo am getting "$scope.imageFile" is null. How can i resolve it in AngularJS v1.2.16 ?


Solution

  • You can upload an extension-less file by setting ngf-pattern to a wildcard (asterisk *)

    <button id="profileImage" ngf-select ng-model="imageFile" 
         ngf-pattern="'*'" ngf-accept="'image/*'" 
         ngf-change="clearImageErrorMsgs()">Change Photo</button>
    

    The pattern you were giving was failing a regexp text because it expected a dot (.).

    Here's a plnkr that demonstrates the use case, however of course the Submit fails with a 400 since I don't have anywhere to upload a file ;)

    Edit Given equivalent files "anon.jpg" and "anon" selecting "anon.jpg" yields scope.file as

    $ngfName: "anon.jpg"
    size:9612
    type:"image/jpeg"
    __proto__: Blob
    

    Compare with the extension-less "anon" file:

    lastModified:1453925356897
    lastModifiedDate:Wed Jan 27 2016 15:09:16 GMT-0500 (Eastern Standard Time)
    name:"anon"
    size:31002
    type:""
    webkitRelativePath:""
    __proto__: File
    

    Please note the difference in the __proto__ properties. Clearly ng-file-upload is treating extension-less (i.e. type-less) files differently.

    All you need to do in your HTML to display the file name selected is something like this where scope.file is the ng-model:

    <span>{{file.$ngfName || file.name}}</span>
    

    I updated the plunkr to demonstrate this, have a look at the code.

    Poking around in the debugger is a time saver.

    If you're not satisfied, you need to file an issue at the github project.