最後圖片上傳的感謝名單盧卡斯科斯塔求助知道我分享我的代碼
第1步:從官方網站上的提示
npm install [email protected]
步驟安裝強大formidable
運行命令2.我的圖片上傳表格.jade
01在我的情況下,你的文件
第3步:添加模塊,我有index.js
var express = require('express');
var router = express.Router();
var util = require("util");
var fs = require("fs");
var formidable = require('formidable');
var path = require('path');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express', dataGet: "data" });
});
router.get('/about', function(req, res, next) {
res.render('index', { title: 'C' });
});
router.get('/imageUpload', function(req, res, next){
res.render('imageUpload', { title: 'Image upload form' });
});
router.post("/upload", function(req, res, next){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
// `file` is the name of the <input> field of type `file`
console.log(files);
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
form.on('error', function(err) {
console.error(err);
});
form.on('progress', function(bytesReceived, bytesExpected) {
var percent_complete = (bytesReceived/bytesExpected) * 100;
console.log(percent_complete.toFixed(2));
});
form.on('end', function(fields, files) {
/* Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/* The file name of the uploaded file */
var file_name = this.openedFiles[0].name;
/* Location where we want to copy the uploaded file */
var new_location = 'F:/node/expressApp/myAppExpress/public/images/';
fs.readFile(temp_path, function(err, data) {
fs.writeFile(new_location + file_name, data, function(err) {
fs.unlink(temp_path, function(err) {
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
});
});
});
});
router.get('/:username', function(req, res) {
// make somethings with username
var username = req.params.username;
console.log("get username"+ username);
});
module.exports = router;
全部完成!希望這將有助於一個:-)
什麼意思'req.files'? –
我發現這個在一些博客如此實現,但這是行不通的,我也嘗試req.body但得到空的結果。 –
這不是在文檔中存在:http://expressjs.com/api.html#req –