节点js在上传到目录之前删除文件

时间:2018-05-16 06:24:12

标签: node.js

我有一个场景,我必须首先删除文件夹中的图像,然后才能在其中上传新图像。这是我的节点JS(服务器)代码

var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose');                 // mongoose for mongodb
var port = process.env.PORT || 8000;                // set the port
var database = require('./config/database');            // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var multer = require('multer');
var messageId = {};
var fs = require('fs');
var router = express.Router();
var UserProfile = require('./app/models/UserProfile.js');
// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.Promise = global.Promise;
mongoose.connection.on('error', function(e) {
    console.log('Can not connect Error:>>',e);
    process.exit();
});
mongoose.connection.once('open', function(d) { 
    console.log("Successfully connected to the database");
})
//app.use(express.static('./public'));      // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  next();
});

 app.use(bodyParser.urlencoded({ extended: false }));
 app.use(bodyParser.json());
 app.use(express.static(path.join(__dirname)));
var upload = multer({dest :'user-img/'});
var profilePic = express.Router();
const directory = 'user-img';

function uploadPic()
{
    fs.readdir(directory, (err, files) => {
        if (err) throw err;

        for (const file of files) {
        fs.unlink(path.join(directory, file), err => {
            if (err) throw err;
        });
        }
    });
    console.log(222);
    profilePic.post('/profilepic' , upload.any() , function(req, res, next)
        {
                console.log(2);                    
                if(req.files)
                {        
                var filename = (new Date).valueOf()+"-"+ req.files[0].originalname;

                    fs.rename(req.files[0].path ,'user-img/'+filename+".jpg", function(err)
                    {
                        res.send(filename);
                            if(err) throw err;          

                            });       
                     }
        });
}


app.use('/upload' , uploadPic);
app.listen(port);

您可能已经注意到,我调用了uploadPic方法,在我有profilePic.post方法的方法中。现在我的profilePic.post方法没有被执行。在我将它分开后,这两个功能都能正常工作。我在这里想念的是什么?我是节点js的新手。

2 个答案:

答案 0 :(得分:0)

方法1

profilePic.post 是路线注册部分。它将在express.Router()对象中注册您的路由。

/ profilepic api作为单独的API开发。在 uploadPic 方法中,使用http客户端库requestwreck进行内部API调用(调用配置文件pic api)。

用例的示例代码结构

app.use('/ upload',uploadPic); app.use('/ profilepic',profilePic)

上传pic api中的逻辑

function uploadPic()
{
    //Logic to delete image inside the folder

    //Using http client libraries for internal api calls   
    var formData = {
        my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
    }
   request.post({url:'http://localhost', formData: formData}, function optionalCallback(err, httpResponse, body) {
      if (err) {
        return console.error('upload failed:', err);
      }
      console.log('Upload successful!  Server responded with:', body);
    });

}
  

注意:它只是一个获得想法的逻辑,而不是一个有效的代码。

方法2 为您的应用程序中的配置文件上传和重用开发可重用的功能

答案 1 :(得分:0)

我设法以不同的方式解决,我在post方法之后检查将忽略新插入的文件并删除其余文件。

以下是修改后的代码段

var upload = multer({dest :'user-img/'});

var profilePic = express.Router();
const directory = 'user-img';
        profilePic.post('/profilepic' , upload.any() , function(req, res, next)
        {

                 if(req.files)
                 {       
                  var filename = (new Date).valueOf()+"-"+ req.files[0].originalname;  

                    fs.rename(req.files[0].path ,'user-img/'+filename+".jpg", function(err)
                    {
                        fs.readdir(directory, (err, files) => {
                            if (err) throw err;                
                            for (const file of files) {                     
                                if(file != filename+".jpg"){                          
                                    fs.unlink(path.join(directory, file), err => {
                                   if (err) throw err;
                                     });
                                }                   
                            }
                        });               

                        res.send(filename);
                            if(err) throw err;                  

                           });        

              }
        });
    app.use('/upload' , profilePic);