简体   繁体   中英

How to upload files outside root folder in nodejs?

I have my project folder on Ubuntu instance at: /workspace/myproject

Till now, I used to store uploaded files at location: /myproject/public/uploads

var fs = require('fs');
var savePath = 'public/uploads/';
var filename = uuid.v4() + '.jpg';
var base64 = new Buffer(requestParams[constant.DATA], 'base64');
fs.writeFile(savePath + filename, base64, function(error) {
});

I want to save my uploaded files at: /workspace/uploads

instead of inside the public folder. Also, I don't want to write absolute path in my code.

Any other idea?

If you want to save a file in a folder within the parent directly, then you could use ../ to go back a level. Like this:

var fs = require('fs');
var savePath = __dirname + '/../uploads/';
var filename = uuid.v4() + '.jpg';
var base64 = new Buffer(requestParams[constant.DATA], 'base64');
fs.writeFile(savePath + filename, base64, function(error) {
    // handle error
});

您可以使用__dirname获取当前目录或./相对路径

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM