загрузка файла с использованием angularjs без $ scope - PullRequest
0 голосов
/ 05 июля 2018

Я новичок в Angular, и я пытаюсь осуществить загрузку логотипа с использованием Angular 1. После выбора файла, если я нажму, загрузить его показ как неопределенный. Пожалуйста, помогите.

Вот мой HTML-код:

 <input type="file" data-file-model="organisationCtrl.filesArray" >
                        <button type="submit" data-ng-click="organisationCtrl.uploadFile()">save</button>

Вот угловая часть: // главный контроллер:

(function() {
    'use strict';
    angular.module('vyahara').controller('OrganisationCtrl', OrganisationCtrl);
    // The $inject property is an array of service names to inject.
    OrganisationCtrl.$inject = [ '$http', '$window', '$location',  '$rootScope',
            'GenericPostService' ];
    function OrganisationCtrl($http, $window, $location, $rootScope,
            GenericPostService) {
        var organisationCtrl = this;

// Проверка имени пользователя (для понимания), которая работает нормально:

organisationCtrl.validUser = validUser;
        function validUser()
        {
            console.log("sdagfsdfgsdfgsdfgsdfgsdfg");
            if (organisationCtrl.userName != null
                    && organisationCtrl.userName != "") {
                if (organisationCtrl.userName.length < 8) {
                    swal('', 'User Id must have 8-15 Chracters', 'warning');
                    organisationCtrl.userName = "";
                }
                var userCreationBean = {
                    "userCreationBean" : {
                        userNumber : organisationCtrl.userName,
                    }
                }
                GenericPostService
                        .post('/user/valid/search', userCreationBean)
                        .then(
                                function(response) {
                                    if (response.statusCode == 200) {
                                        swal('', 'User Name Already Taken',
                                                'warning');
                                        organisationCtrl.userName = "";

                                    } else {
                                        organisationCtrl.userName = organisationCtrl.userName;
                                    }

                                });

            }
        }

// загрузка файла не работает

organisationCtrl.uploadFile = uploadFile;
        function uploadFile() {

                var fileUpload = new FormData();
                console.log("You are In!!!!",organisationCtrl.filesArray);
                fileUpload.append("fileUpload", organisationCtrl.filesArray);
                console.log(">>>>>>>>>>",fileUpload);
                GenericPostService.postWithConfig('/organization/createFile',  fileUpload, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                })
                .then(
                        function(response) {
                            if (response.statusCode == 200) {
                                swal('', 'File Upload Successful');

});

1 Ответ

0 голосов
/ 05 июля 2018

Существует много модулей Angularjs для загрузки файлов, вы просто должны включить их в свой код. Таким образом, вы не будете усложнять код. Ниже приведены ссылки, на которые вы можете сослаться:

https://github.com/leon/angular-upload

https://github.com/nervgh/angular-file-upload/

https://github.com/danialfarid/ng-file-upload

https://github.com/radify/angular-file

http://www.folio3.com/blog/angularjs-file-upload-example-tutorial/

или вы можете просто пойти дальше ->

npm install ng-file-upload 

включает некоторые теги сценариев

<script src="angular(.min).js"></script>
<script src="ng-file-upload-shim(.min).js"></script> <!-- for no html5 browsers support -->
<script src="ng-file-upload(.min).js"></script>


Upload on form submit or button click
<form ng-app="fileUpload" ng-controller="MyCtrl" name="form">
  Single Image with validations
  <div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'"
    ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" 
    ngf-resize="{width: 100, height: 100}">Select</div>
  Multiple files
  <div class="button" ngf-select ng-model="files" ngf-multiple="true">Select</div>
  Drop files: <div ngf-drop ng-model="files" class="drop-box">Drop</div>
  <button type="submit" ng-click="submit()">submit</button>
</form>

Upload right away after file selection:
<div class="button" ngf-select="upload($file)">Upload on file select</div>
<div class="button" ngf-select="uploadFiles($files)" multiple="multiple">Upload on file select</div>
  Drop File:
<div ngf-drop="uploadFiles($files)" class="drop-box"
  ngf-drag-over-class="'dragover'" ngf-multiple="true" 
  ngf-pattern="'image/*,application/pdf'">Drop Images or PDFs files here</div>
<div ngf-no-file-drop>File Drag/Drop is not supported for this browser</div>

Image thumbnail: <img ngf-thumbnail="file || '/thumb.jpg'">
Audio preview: <audio controls ngf-src="file"></audio>
Video preview: <video controls ngf-src="file"></video>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...