簡體   English   中英

如何在將圖像上傳到服務器時傳遞多個值(使用 AngularJS 和 NodeJS 上傳文件)?

[英]How to pass multiple values while uploading image to server(File Upload with AngularJS and NodeJS)?

客戶端:

我已經使用 AngularJS 和 NodeJS 完成了文件上傳,它正在工作,但是在上傳文件時我需要將“名稱”和“電子郵件”傳遞給服務器。

服務器端:

將文件上傳到文件夾后,我需要將文件路徑、名稱和電子郵件保存到數據庫中。 我怎樣才能做到這一點?

 angular.module('fileUpload', ['ngFileUpload']) .controller('MyCtrl',['Upload','$window',function(Upload,$window){ var vm = this; vm.submit = function(){ //function to call on form submit if (vm.upload_form.file.$valid && vm.file) { //check if from is valid vm.upload(vm.file); //call upload function } } vm.upload = function (file) { console.log(vm.name); console.log(vm.email); Upload.upload({ url: 'http://localhost:3000/upload', //webAPI exposed to upload the file data:{file:file} //pass file as data, should be user ng-model }).then(function (resp) { //upload function returns a promise if(resp.data.error_code === 0){ //validate success $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: '); } else { $window.alert('an error occured'); } }, function (resp) { //catch error console.log('Error status: ' + resp.status); $window.alert('Error status: ' + resp.status); }, function (evt) { console.log(evt); var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name); vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress }); }; }]);
 <script src="http://cdn.bootcss.com/danialfarid-angular-file-upload/12.2.13/ng-file-upload-shim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-file-upload/2.4.1/angular-file-upload.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <html> <head> <title>Home</title> </head> <body ng-app="fileUpload"> <h1>Angular Node File Upload</h1> <form ng-controller="MyCtrl as up" name="up.upload_form"> name <input type="text" ng-model="up.name"><br> <br> email <input type="text" ng-model="up.email"><br> Image <input type="file" ngf-select ng-model="up.file" name="file" ngf-max-size="20MB" /> Image thumbnail: <img style="width:100px;" ng-show="!!up.file" ngf-thumbnail="up.file || '/thumb.jpg'"/> <i ng-show="up.upload_form.file.$error.required">*required</i><br> <i ng-show="up.upload_form.file.$error.maxSize">File too large {{up.file.size / 1000000|number:1}}MB: max 20M</i> <!-- Multiple files <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div> Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> --><br> <button type="submit" ng-click="up.submit()">submit</button> <p>{{up.progress}}</p> </form> </body> </html>

后台代碼:

var express = require('express'); 
var app = express(); 
var bodyParser = require('body-parser');
var multer = require('multer');

app.use(function(req, res, next) { //allow cross origin requests
    res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Allow-Origin", "http://localhost");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

/** Serving from the same express Server
No cors required */
app.use(express.static('../client'));
app.use(bodyParser.json());  

var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/');
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]);
    }
});

var upload = multer({ //multer settings
                storage: storage
            }).single('file');

/** API path that will upload the files */
app.post('/upload', function(req, res) {
    console.log(req.body);
    upload(req,res,function(err){
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
         res.json({error_code:0,err_desc:null});
    });
});

app.listen('3000', function(){
    console.log('running on 3000...');
});

我試過這樣

Upload.upload({
        url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
        data:{file:file, name:vm.name, email:vm.email} //pass file as data, should be user ng-model
    })

后端

app.post('/upload', function(req, res) {
        console.log(req.body);
        console.log(req.file);
      upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
             res.json({error_code:0,err_desc:null});
        });
    });

在前端(angular)我得到了我在表單中輸入的值但后端(nodejs)我得到了未定義的值在此處輸入圖片說明 在此處輸入圖片說明

您需要修改您的角度代碼以發送請求數據中的額外信息

Upload.upload({
        url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
        data:{file:file, name:vm.name, email:vm.email} //pass file as data, should be user ng-model
    })

然后在您的后端代碼中,您可以在請求正文中引用它

req.body.name
req.body.email

您可以添加一個文件屬性來保存file並更新data property to contain email and nameUpload.upload對象中data property to contain email and name 這樣您就可以在服務器端輕松獲取它們。

注意:我已經更新了我的答案,我將Angular view發出的所有值都包裝在一個params對象中。 我還更改了 angular-ng-upload CDN 不適用於 codepen。 您還應該首先加載Angular.js

看法

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script>
<html>
    <head>
        <title>Home</title>
    </head>
    <body ng-app="fileUpload">
        <h1>Angular Node File Upload</h1>
        <form  ng-controller="MyCtrl as up" name="up.upload_form">

            name    
            <input type="text" ng-model="up.params.name"><br> <br>
            email   
            <input type="text" ng-model="up.params.email"><br> 
            Image 
            <input 
                type="file" 
                ngf-select 
                ng-model="up.params.file" 
                name="file" 
                ngf-max-size="20MB" 
                />
            Image thumbnail: <img style="width:100px;" ng-show="!!up.params.file" ngf-thumbnail="up.params.file || '/thumb.jpg'"/>
            <i ng-show="up.upload_form.params.file.$error.required">*required</i><br>
            <i ng-show="up.upload_form.params.file.$error.maxSize">File too large 
            {{up.params.file.size / 1000000|number:1}}MB: max 20M</i>
           <!--  Multiple files
            <div class="button" ngf-select ng-model="up.files" ngf-multiple="true">Select</div>
            Drop files: <div ngf-drop ng-model="up.files" class="drop-box">Drop</div> --><br> 
            <button type="submit" ng-click="up.submit()">submit</button>
            <p>{{up.progress}}</p>
            <p>{{up.params}}{{up.params.file.size}}</p>
        </form>
    </body>

</html>

var vm = this;

vm.submit = function(){ 
   if (vm.upload_form.file.$valid && vm.params.file) {
       console.log(vm.params)
       vm.upload(vm.params); // Pass the `vm.params` object.
   }
 }

vm.upload = function (params) {

    console.log(params.name); // params.name should be available
    console.log(params.email); // params.email should be available
    console.log(params.file); // params.file should be available

    Upload.upload({
      url: 'http://localhost:3000/upload',
      file: params.file,   // Image to upload
      data: {
        name: params.name,
        email: params.email
      } 
    })
}

Node.js/express

app.post('/upload', function(req, res) {
    console.log(JSON.parse(req.body.data)); // email and name here
    console.log(req.files.file); // file object

    upload(req,res,function(err){
        if(err){
             res.json({error_code:1,err_desc:err});
             return;
        }
         res.json({error_code:0,err_desc:null});
    });
});

我不確定我的回答是否對你有幫助。 但是您可以在數據中添加姓名和電子郵件。

Upload.upload({
            url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
            data:{file:file,name:"putHeretheName",email:"putHereTheMail"} //pass file as data, should be user ng-model
        }

然后服務器端您可以創建一個函數或完成您的實際“/上傳”查詢,將您想要的內容保存在您的 bdd 中。 您只需要獲取創建的路徑的名稱,然后在上傳成功的情況下進行保存。

也許這個例子會幫助你更多: https : //www.npmjs.com/package/ng-file-upload

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM