2017-08-06 2 views
0

Ich benutze tatsächlich diese Arbeits Multer-Code zum Hochladen von Datei. Aber ich möchte mit ng-click() mehr Dinge von meinem Controller mit $ http Post senden. Eine einfache Eingabe mit einer Schaltfläche wird die beste sein.Multer Bild ohne Formular hochladen mit NG-Klick

html-Seite:

<form method="post" enctype="multipart/form-data" action="/productimage"> 
     <p> 
     <input type="file" id="imgadd" name="upl"/> 
     </p> 
     <p> 
     <input type="submit"/> 
     </p> 
</form> 

Server-Seite:

var storage = multer.diskStorage({ 
    destination: function (req, file, cb) { 
    cb(null, './uploads/products') 
    }, 
    filename: function (req, file, cb) { 
    cb(null, Date.now() + '.jpg') //Appending .jpg 
    } 
}) 

app.post('/productimage', multer({ storage: storage, limits: { fileSize: 200000} }).single('upl'), function(req,res, error){ 
    console.log(req.body); //form fields 
    /* example output: 
    { title: 'abc' } 
    */ 
    console.log(req.file.filename); //form files 
    /* example output: 
      { fieldname: 'upl', 
       originalname: 'grumpy.png', 
       encoding: '7bit', 
       mimetype: 'image/png', 
       destination: './uploads/', 
       filename: '436ec561793aa4dc475a88e84776b1b9', 
       path: 'uploads/436ec561793aa4dc475a88e84776b1b9', 
       size: 277056 } 
    */ 
    res.status(204).end(); 
}); 

Antwort

0

Versuchen Sie, eine Richtlinie, wie unten

.directive('fileModel', ['$parse', function($parse) { 
     function fn_link(scope, element, attrs) { 
      var onChange = $parse(attrs.fileModel); 
      element.on('change', function (event) { 
       onChange(scope, { $files: event.target.files }); 
      }); 
     }; 
     return { 
      link: fn_link 
     } 
    }]) 

zu verwenden, dann input type ersetzen = Datei zu

<input type="file" id="fileId" accept="image/*" file-model="myFiles($files)"/> 

und dann in Ihrem Controller fügen Sie diese

var formData = new FormData(); 
$scope.myFiles = function($files) { 
    formData.append('upl', $files[0]); 
} 

‚upl‘ Ersetzen auf einen Namen, die Sie wollen, dass es wie in Backend , wenn Sie wollen etwas hinzufügen, fügen Sie jeder Werte mit Schlüsselwertpaar in & Formdata als

formData.append('name', form.name); 
formData.append('title', form.title); 
senden

** Ihr Bild direkt anhängen wird aber denken Sie daran, dass die Daten auf Ihrer Funktion anhängen werden sollten, die ** von NG-CLICK genannt wird

Jetzt Methode, um Ihre $ http

$http.post('/productimage', formData,{headers:{'Content-Type': undefined}}).then(...) 

** Nach erfolgreicher Einreichung Vergessen Sie nicht, formData als ** zu löschen formData.delete ('name');

Knoten Side

app.post('/productimage', multer({ storage: storage, limits: { fileSize: 200000} }).single('upl'), function(req,res, error){ 
    console.log(req.body); 
/*{title: 'xyz', name:'abc'} 
*/ 
    console.log(req.file); 
    res.status(204).end(); 
}); 
Verwandte Themen