文件上传下载

shp文件上传,formidable

安装formidable:


npm i -S formidable

安装unzip模块

npm i -S unzip

上传一个shp压缩文件至服务器,在服务器端解压后入库。
需要注意1、form.uploadDir='path',这个path是已经存在的目录

 var ls = childProcess.exec('shp2pgsql -c -g geom -D -s 3857 -S -i -I  '+ com_path + '| psql -p 5433 -U postgres -d test');
var fs=require('fs');
var util=require('util');
var path=require('path');
var unzip = require("unzip");
var childProcess=require('child_process');
const formidable = require('formidable');
exports.upload=function (req,res) {
    const form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = "test";
    form.keepExtensions = true;
    fields=[];
    files=[];
    form
        .on('field', function (field, value) {
            //console.log(field, value);
            fields.push([field, value]);
        })
        .on('file', function (field, file) {
           // console.log(field, file);
            files.push([field, file]);
        })
        .on('end', function () {
            console.log('-> upload done');
            res.writeHead(200, {'content-type': 'text/plain'});
            res.write('received fields:\n\n ' + util.inspect(fields));
            res.write('\n\n');
            res.end('received files:\n\n ' + util.inspect(files));
            var ppath=files[0][1].path;
            var tmp_path=ppath.substring(0,ppath.length-4);
            console.log(tmp_path);
            var filename=files[0][1].name.replace('.zip','.shp');
            fs.mkdir(tmp_path, 0777, function(err){
                if(err){
                    console.log(err);
                }else{
                    console.log("creat done!");
                }
            });
            var rootdir=path.dirname(__dirname);
            var com_path=path.join(rootdir,tmp_path,filename);
            var file2=fs.createReadStream(files[0][1].path).pipe(unzip.Extract({ path:tmp_path}));
            console.log('shp2pgsql -c -g geom -D -s 3857 -S -i -I  '+com_path + '| psql -p 5433 -U postgres -d test');
            var ls = childProcess.exec('shp2pgsql -c -g geom -D -s 3857 -S -i -I  '+ com_path + '| psql -p 5433 -U postgres -d test');
        });
    form.parse(req);
}

等价于:

var fs=require('fs');
var util=require('util');
var path=require('path');
var unzip = require("unzip");
var childProcess=require('child_process');
const formidable = require('formidable');
exports.upload=function (req,res) {
    const form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = "test";
    form.keepExtensions = true;
 form.parse(req, function(err, fields, files) {
        if(err){
            throw err;
        }
        var ppath=files.upload.path;
        console.log(ppath);
        var tmp_path=ppath.substring(0,ppath.length-4);
        var file2=fs.createReadStream(files.upload.path).pipe(unzip.Extract({ path:tmp_path}));
    });
}

你可能感兴趣的:(文件上传下载)