Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了meanjs – 使用Angular-file-upload将图片添加到MEAN.JS示例大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用MEAN.JS( https://github.com/meanjs/mean)和angular-file-upload( https://github.com/danialfarid/angular-file-upload). @H_498_1@mEAN.JS提供的“Article”样本包含两个名为“title”和“content”的字段.我想修改它并添加一个图片”字段,允许用户上传图片.

我知道我必须在MEAN.JS中修改3个文件

~myproject/app/models/article.server.model.js 
~myproject/public/modules/articles/controllers/articles.CLIENt.controller.js
~myproject/public/modules/articles/views/create-article.client.view.html

但是,我无法成功修改它们.

@H_404_9@
@H_404_9@
我的解决方案在客户端上使用 angular-file-upload并使用 connect-multiparty来处理文件上载.

图像直接存储在数据库中,这限制了它们的大小.我没有包含检查图像大小所需的代码.

建立

bower install ng-file-upload --save
 bower install ng-file-upload-shim --save 

 npm i connect-multiparty
 npm update

all.js
添加angular-file-upload脚本

...
            'public/lib/ng-file-upload/FileAPI.min.js','public/lib/ng-file-upload/angular-file-upload-shim.min.js','public/lib/angular/angular.js','public/lib/ng-file-upload/angular-file-upload.min.js',...

config.js
注入angular-file-upload依赖项

...
var applicationModuleVendorDependencies = ['ngresource','ngAnimate','ui.router','ui.bootstrap','ui.utils','angularFileUpload'];
...

article.client.controller.js
使用angular-file-upload依赖项

angular.module('articles').controller('ArticlesController',['$scope','$timeout','$upload','$stateParams','$LOCATIOn','Authentication','Articles',function($scope,$timeout,$upload,$stateParams,$LOCATIOn,Authentication,Articles) {
    $scope.fileReaderSupported = window.FileReader !== null;



    // Create new Article
            $scope.create = function(picFilE) {
          console.log('create');
                      console.log(picFilE);
        var article = new Articles({
            title: this.title,content: this.content,image: null
        });

         console.log(articlE);
         $upload.upload({
            url: '/articleupload',method: 'POST',headers: {'Content-Type': 'multipart/form-data'},fields: {article: articlE},file: picFile,}).success(function (response,status) {
              $LOCATIOn.path('articles/' + response._id);

            $scope.title = '';
            $scope.content = '';
        }).error(function (err) {
                $scope.error = err.data.message;
        });

    };

    $scope.doTimeout = function(filE) {
         console.log('do timeout');
        $timeout( function() {
                var fileReader = new FileReader();
                fileReader.readAsDataURL(filE);
             console.log('read');
                fileReader.onload = function(E) {
                    $timeout(function() {
                        file.dataUrl = e.target.result;
                         console.log('set url');
                    });
                };
            });
    };


    $scope.generateThumb = function(filE) {
        console.log('generate Thumb');
    if (filE) {
        console.log('not null');
         console.log(filE);
        if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
            $scope.doTimeout(filE);
          }
      }
   };
}

创建-article.client.view.html
更新创建视图以处理文件选择和上载

<section data-ng-controller="ArticlesController">
<div class="page-header">
    <h1>New Article</h1>
</div>
<div class="col-md-12">
    <form name="articleForm" class="form-horizontal" data-ng-submit="create(picFilE)" novalidate>
        <fieldset>
            <div class="form-group" ng-class="{ 'has-error':   articleForm.title.$dirty && articleForm.title.$invalid }">
                <label class="control-label" for="title">title</label>
                <div class="controls">
                    <input name="title" type="text" data-ng-model="title" id="title" class="form-control" placeholder="title" required>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label" for="content">Content</label>
                <div class="controls">
                    <textarea name="content" data-ng-model="content" id="content" class="form-control" cols="30" rows="10" placeholder="Content"></textarea>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label" for="articleimage">Article Picture</label>
                <div class="controls">
                     <input id="articleimage" type="file" ng-file-SELEct="" ng-model="picFile" name="file" accept="image/*" ng-file-change="generateThumb(picFile[0],$files)" required="">
                    <br/>
                    <img ng-show="picFile[0].dataUrl != null" ng-src="{{picFile[0].dataUrl}}" class="img-thumbnail" height="50" width="100">
                    <span class="progress" ng-show="picFile[0].progress >= 0">      
                        <div style="width:{{picFile[0].progress}}%" ng-bind="picFile[0].progress + '%'" class="ng-binding"></div>
                    </span> 
                    <span ng-show="picFile[0].result">Upload successful</span>
                </div>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-default" ng-disabled="!articleForm.$valid" ng-click="uploadPic(picFilE)">
            </div> 
            <div data-ng-show="error" class="text-danger">
                <strong data-ng-bind="error"></strong>
            </div>
        </fieldset>
    </form>
</div>
</section>

视图article.client.view.html
更新列表视图以包含图像

<img ng-src="data:image/jpeg;base64,{{article.imagE}}" id="photo-id" width="200" height="200"/>

列表articles.CLIENt.view.html
更新视图以包含imgae

<img ng-src="data:image/jpeg;base64,{{article.imagE}}" id="photo-id" width="40" height="40"/>

article.server.model.js
将图像添加数据库模型

...
image: {
    type: String,default: ''
},...

article.server.routes.js
添加上传路由@R_489_10499@nnect-multiparty

...
multiparty = require('connect-multiparty'),multipartymiddleware = multiparty(),...
app.route('/articleupload')
    .post(users.requiresLogin,multipartymiddleware,articles.createWithUpload);
...

article.server.controller.js
处理上传新路线需要fs

...
fs = require('fs'),...
/**
 * Create a article with Upload
 */
exports.createWithUpload = function(req,res) {
 var file = req.files.file;
 console.log(file.Name);
 console.log(file.typE);
 console.log(file.path);
 console.log(req.body.articlE);

var art = JSON.parse(req.body.articlE);
var article = new Article(art);
article.user = req.user;

fs.readFile(file.path,function (err,original_data) {
 if (err) {
      return res.status(400).send({
            message: errorHandler.getErrormessage(err)
        });
  } 
    // save image in db as base64 encoded - this limits the image size
    // to there should be size checks here and in client
  var base64Image = original_data.toString('base64');
  fS.Unlink(file.path,function (err) {
      if (err)
      { 
          console.log('Failed to delete ' + file.path);
      }
      else{
        console.log('successfully deleted ' + file.path);
      }
  });
  article.image = base64Image;

  article.save(function(err) {
    if (err) {
        return res.status(400).send({
            message: errorHandler.getErrormessage(err)
        });
    } else {
        res.json(articlE);
    }
  });
});
};
...
@H_404_9@
本图文内容来源于网友网络收集整理提供,作为学习参使用,版权属于原作者。

大佬总结

以上是大佬教程为你收集整理的meanjs – 使用Angular-file-upload将图片添加到MEAN.JS示例全部内容,希望文章能够帮你解决meanjs – 使用Angular-file-upload将图片添加到MEAN.JS示例所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。