Upload files with Multer without using action, method, encrypt=“multipart/form-data” attributes on form tag

坚强是说给别人听的谎言 提交于 2020-01-17 07:43:11

问题


so I'm trying to upload an image with Multer but I want to use Angular's $http.post to upload the file. Not have a submit button trigger the form method and action. The problem is if I do not use encrypt, method or post attributes the req.file ends up being undefined and the image does not show up in the uploads folder.

So my question is, is there any way I can use Multer file upload not by the regular form method with action but angular's $http.post(). When I do it now the req.file is always undefined.

Here's my code for reference

app.js (Node)

var express = require('express');
var http    = require('http');
var path    = require('path');
var fs      = require('fs');
var crypto = require('crypto');
var multer  = require('multer');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.port || 8080;

app.set('view engine', 'ejs');
app.use('/assets', express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

var path = require('path');
var multer = require('multer');

var storage = multer.diskStorage({
  destination: './public/uploads/',
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      if (err) { return cb(err); }
            cb(null, raw.toString('hex') + path.extname(file.originalname));
    });
  }
});

var upload = multer({ storage: storage });

app.get('/', function (req, res) {
    'use strict';
    res.render('index', {filename: filename });
});

app.post('/', function (req, res) {
    'use strict';
});

app.post('/upload', upload.single('image'), function (req, res) {
    filename = req.files;
    console.log(req.files);
});

app.listen(port);

HTML Form:

<form action="/upload" method="post" encrypt="multipart/form-data">
<div class="form-group">
<label for="image">Choose Image</label>
<input id="inputImage" name="image" type="file">
<button class="form-control" ng-click="uploadFile()">Add</button>
</form>

So I basically want to remove this default behaviour and still get the req.file object.

And finally my Angular code:

$scope.uploadFile = function(){
        var file = $scope.myFile;
        var uploadUrl = "/upload";
        var fd = new FormData();
        fd.append('file', file);

        $http.post(uploadUrl,fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
        })
        .success(function(){
            console.log("success!!");
        })
        .error(function(){
            console.log("error!!");
        });
    };

Please help me on this... Right now I get the $http.post() .error() callback and if I dig deep into it, it is because req.file is undefined in my node app.js


回答1:


Why you are using headers: {'Content-Type': undefined} You should send content type for images instead of undefined Or else remove that header and try. Also by using console.log(req.body) u can check what body ur submitting



来源:https://stackoverflow.com/questions/42508558/upload-files-with-multer-without-using-action-method-encrypt-multipart-form-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!