簡體   English   中英

如何在Node.js中上傳圖片

[英]How to upload image in Node.js

我對Node.js完全是新手,我只想像在php中一樣使用ajax學習上傳和顯示圖像。我發現大多數教程對我來說都很困難。開始之前,我嘗試使用此代碼

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


//all environment
app.use(bodyParser())



var form = "<!DOCTYPE HTML><html><body>" +
"<form method='post' action='/upload' enctype='multipart/form-data'>" +
"<input type='file' name='image'/>" +
"<input type='submit' /></form>" +
"</body></html>";

app.get('/', function (req, res){
    res.writeHead(200, {'Content-Type': 'text/html' });
    res.end(form);

});
/// Post files
app.post('/upload', function(req, res) {
    console.log('Hello world');
       console.log(req.files);
});


app.listen(8080)

但是對於req.files來說是不確定的。有人能說出原因嗎?如果這是一個愚蠢的問題,請原諒我,還請您提供一些資源,在此先感謝您。

req.files適用於Express v3,您正在使用v4。

現在,body-parser僅處理urlencoded和json主體。 對於多部分實體,應使用替代方法。

https://github.com/expressjs/body-parser

例如與multer:

var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'}))

/// Post files
app.post('/upload', function(req, res) {
    console.log('Hello world');
    console.log(req.files);
});

app.listen(8080)

在express 4中, busboy是處理上傳圖像的絕佳方法。 讓我們看一下Miaou的一個簡化示例

exports.appPostUpload = function(req, res){
    var busboy = new Busboy({ headers: req.headers }), files=[];
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        var chunks = [];
        file.on('data', function(chunk) {
            chunks.push(chunk);             
            // todo : abort if sum of chunk.lengths is too big (and tell the client he's fat)
        });
        file.on('end', function() {
            files.push({name:fieldname, bytes:Buffer.concat(chunks)});
        });
    }).on('finish', function() {
        if (!files.length) {
            return res.send({error:'found nothing in form'});
        }
        // we can now work with the items in `files` like you normally would.
    });
    req.pipe(busboy);       
}

暫無
暫無

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

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