recherche

Maison  >  Questions et réponses  >  le corps du texte

angulaire.js - Le type de contenu de la publication angulaire est défini, ce qui entraîne l'impossibilité de télécharger des images. Aidez-moi ! !

Le code suivant est défini dans le projet angulaire pour certaines raisons :

    // $locationProvider.html5Mode(true);

    $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

    /**
     * The workhorse; converts an object to x-www-form-urlencoded serialization.
     * @param {Object} obj
     * @return {String}
     */
    var param = function (obj) {
      var query = '', name, value, fullSubName, subName, subValue, innerObj, i;

      for (name in obj) {
        value = obj[name];

        if (value instanceof Array) {
          for (i = 0; i < value.length; ++i) {
            subValue = value[i];
            fullSubName = name + '[' + i + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if (value instanceof Object) {
          for (subName in value) {
            subValue = value[subName];
            fullSubName = name + '[' + subName + ']';
            innerObj = {};
            innerObj[fullSubName] = subValue;
            query += param(innerObj) + '&';
          }
        }
        else if (value !== undefined && value !== null)
          query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
      }

      return query.length ? query.substr(0, query.length - 1) : query;
    };

    // Override $http service's default transformRequest
    $httpProvider.defaults.transformRequest = [function (data) {
      return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data;
    }];

Par conséquent, les fichiers ne peuvent pas être téléchargés pour le moment, et même la soumission de formulaire la plus simple ne fonctionne pas :

  <form action="upload/url" name="form1" method="post" enctype="multipart/form-data">
    <input id="file" name="file" type="file" accept="image/*">
    <button type="submit" class="btn btn-primary btn-lg">提交</button>
  </form>

Demandant l'aide de tous les experts, comment puis-je télécharger des photos normalement ? Urgent, très urgent, le projet a pris du retard d'un jour... Merci !

漂亮男人漂亮男人2819 Il y a quelques jours811

répondre à tous(3)je répondrai

  • 漂亮男人

    漂亮男人2017-05-15 17:12:24

    https://github.com/nervgh/ang... Prenez-le, de rien

     showUpload: function (todo) {
                    $uibModal.open({
                        animation: true,
                        size: 'lg',
                        templateUrl: 'app/theme/components/upload/upload.html',
                        controller: function ($scope, FileUploader) {
                            var uploader = $scope.uploader = new FileUploader({
                                url: basePath+'/admin/images/upload'
                            });
                            $scope.confirm=function () {
                                console.log(uploader)
                                if(uploader.queue.length<1){
                                    toastr.info('请选择上传图片');
                                    return
                                }
                                uploader.queue[0].upload();
                            }
                            // FILTERS
                            uploader.filters.push({
                                name: 'imageFilter',
                                fn: function (item, options) {
                                    var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
                                    return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                                }
                            });
                            // CALLBACKS
                            uploader.onAfterAddingFile = function (fileItem) {
                                //console.info('onAfterAddingFile', fileItem);
                            };
                            uploader.onSuccessItem = function (fileItem, response, status, headers) {
                                if(response.success){
                                    toastr.info('上传成功');
                                    todo(response);
                                    $scope.$dismiss();
                                }
                            };
                            uploader.onErrorItem = function (fileItem, response, status, headers) {
                                toastr.info('上传失败!');
                            };
                        }
                    });
                }
    (function () {
        'use strict';
    
      
            app.directive('ngThumb', ngThumb).directive('fileInputStyle', fileInputStyle);
    
        /** @ngInject */
        function ngThumb($window) {
            var helper = {
                support: !!($window.FileReader && $window.CanvasRenderingContext2D),
                isFile: function (item) {
                    return angular.isObject(item) && item instanceof $window.File;
                },
                isImage: function (file) {
                    var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                    return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
                }
            };
    
            return {
                restrict: 'A',
                template: '<canvas/>',
                link: function (scope, element, attributes) {
                    if (!helper.support) return;
    
                    var params = scope.$eval(attributes.ngThumb);
    
                    if (!helper.isFile(params.file)) return;
                    if (!helper.isImage(params.file)) return;
    
                    var canvas = element.find('canvas');
                    var reader = new FileReader();
    
                    reader.onload = onLoadFile;
                    reader.readAsDataURL(params.file);
    
                    function onLoadFile(event) {
                        var img = new Image();
                        img.onload = onLoadImage;
                        img.src = event.target.result;
                    }
    
                    function onLoadImage() {
                        var width = params.width || this.width / this.height * params.height;
                        var height = params.height || this.height / this.width * params.width;
                        canvas.attr({width: width, height: height});
                        canvas[0].getContext('2d').drawImage(this, 0, 0, width, height);
                    }
                }
            };
        }
    
        function fileInputStyle() {
            return {
                restrict: 'A',
                link: function ($scope, element, attrs) {
                    bind_button(make_form(element, '选择文件'));
                    function make_form($el, text) {
                        $el.wrap('<p></p>');
                        $el.hide();
                        $el.after('<p class="input-append input-group"><span class="input-group-btn"><button class="btn btn-default" type="button">' + text + '</button>\
                            </span><input class="input-large form-control" name="textfiles" type="text"></p>');
                        return $el.parent();
                    };
                    function bind_button($wrap) {
                        $wrap.find('.input-append').click(function (e) {
                            e.preventDefault();
                           $wrap.find('input[type="file"]').click();
                        });
                    };
                }
            };
        }
    })();
    <p class="modal-content">
        <p class="modal-header">
            <button type="button" class="close" ng-click="$dismiss()" aria-label="Close">
                <em class="ion-ios-close-empty sn-link-close"></em>
            </button>
            <h4 class="modal-title" id="myModalLabel">上传图片</h4>
        </p>
        <p class="modal-body">
            <form name="uploadForm">
                <p class="form-group">
                    <p class="col-sm-12">
                        <input type="file" nv-file-select uploader="uploader" file-input-style/><br/>
                        <table class="table">
                            <thead>
                            <tr>
                                <th width="30%">名称</th>
                                <th ng-show="uploader.isHTML5">大小</th>
                                <th ng-show="uploader.isHTML5">进度</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                            </thead>
                            <tbody>
                            <tr ng-repeat="item in uploader.queue">
                                <td>
                                    <strong>{{ item.file.name }}</strong>
                                    <p ng-show="uploader.isHTML5" ng-thumb="{ file: item._file, height: 100 }"></p>
                                </td>
                                <td ng-show="uploader.isHTML5" nowrap>{{ item.file.size/1024/1024|number:2 }} MB</td>
                                <td ng-show="uploader.isHTML5">
                                    <p class="progress" style="margin-bottom: 0;">
                                        <p class="progress-bar" role="progressbar"
                                             ng-style="{ 'width': item.progress + '%' }"></p>
                                    </p>
                                </td>
                                <td class="text-center">
                                    <span ng-show="item.isSuccess"><i class="glyphicon glyphicon-ok"></i></span>
                                    <span ng-show="item.isCancel"><i class="glyphicon glyphicon-ban-circle"></i></span>
                                    <span ng-show="item.isError"><i class="glyphicon glyphicon-remove"></i></span>
                                </td>
                                <td nowrap>
                                    <button type="button" class="btn btn-success btn-xs" ng-click="item.upload()"
                                            ng-disabled="item.isReady || item.isUploading || item.isSuccess">
                                        <span class="glyphicon glyphicon-upload"></span> 上传
                                    </button>
                                    <button type="button" class="btn btn-warning btn-xs" ng-click="item.cancel()"
                                            ng-disabled="!item.isUploading">
                                        <span class="glyphicon glyphicon-ban-circle"></span> 取消上传
                                    </button>
                                    <button type="button" class="btn btn-danger btn-xs" ng-click="item.remove()">
                                        <span class="glyphicon glyphicon-trash"></span> 移除
                                    </button>
                                </td>
                            </tr>
                            </tbody>
                        </table>
                    </p>
                </p>
            </form>
        </p>
        <p class="modal-footer">
            <button type="button" class="btn btn-primary" ng-click="$dismiss()">关闭</button>
            <button type="button" class="btn btn-info" ng-click="confirm()">确定</button>
        </p>
    </p>
    
    
    
    
    
    
    

    répondre
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-15 17:12:24

    Le sujet a posé deux questions : 1. Pourquoi les paramètres d'en-tête ont-ils été effectués 2. Comment télécharger des photos

    ?

    1. Pourquoi devez-vous définir l'en-tête ? Ajouter le paramètre d'en-tête au niveau de base httpProvider

    http://stackoverflow.com/ques...

    Les programmeurs d'entreprise devraient se référer à cette question. L'interaction API back-end de votre entreprise utilise Content-Type : x-www-form-urlencoded et angulaire utilise Content-type : application/json. Le type de contenu et la sérialisation ont donc été modifiés. Le sujet peut s'y référer.

    2. Télécharger des photos
    La description du sujet n'est pas très claire quant à la manière dont cette soumission a été initiée. Mais le problème vient du fait que le type de contenu du fichier soumis est mal défini. Fournissez un moyen de soumettre en utilisant FormData :

    
    var fd = new FormData();
    fd.append('file', file);
    
    $http.post(uploadUrl, fd, {
       transformRequest: angular.identity,
       headers: {'Content-Type': undefined}
    })
    .success(function(){
    })
    .error(function(){
    });
    

    répondre
    0
  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:12:24

    Votre code js consiste à encoder les données sous forme x-www-form-urlencoded. Mais il n’y a pas de liaison de données dans votre code HTML, ce qui n’est certainement pas possible ! Je soupçonne donc que vous n’avez pas du tout compris l’utilisation d’angularjs.
    De plus, vous n’avez pas expliqué clairement comment vous avez publié les données. Qui sait où se situe votre problème ?

    Revenez après avoir posté le code complet

    répondre
    0
  • Annulerrépondre