node实现文件持久化

 

 

 

1、场景一:表单提交,保存到本地

初始化表单

<form class="form-horizontal" role="form" enctype="multipart/form-data" method="POST"
    action="/contest/vacation-photo/{year}/{month}">
    {{!-- 此处使用了handlebars模板渲染引擎,即为一个路由 --}}
    <div class="form-group">
        <label for="fieldName" class="col-sm-2 control-label">Name</label>
        <div class="col-sm-4">
            <input type="text" class="form-control" id="fieldName" name="name">
        </div>
    </div>
    <div class="form-group"><label for="fieldEmail" class="col-sm-2 control-label">Email</label>
        <div class="col-sm-4">
            <input type="email" class="form-control" required id="fieldName" name="email">
        </div>
    </div>
    <div class="form-group">
        <label for="fieldPhoto" class="col-sm-2 control-label">Vacation photo
        </label>
        <div class="col-sm-4">
            <input type="file" class="form-control" required accept="image/*" id="fieldPhoto" name="photo">
        </div>
    </div>
    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-4">
            {{!-- button的type设置为submit,点击后会自动提交表单, --}}
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </div>
</form>

在这里插入图片描述

提交表单,路由获取请求

安装表单解析模块,将复杂的表单数据格式化,条理化
npm i formidable --save

// 处理带文件上传的表单
app.post("/contest/vacation-photo/:year/:month", function(req, res) {
  // 调用formidale格式化请求的文件
  var form = new formidable.IncomingForm();
  form.parse(req, function(err, fields, files) {
    if (err) return res.redirect(303, "/error");
    // 此处__dirname为项目根目录,创建保存文件目录
    var dataDir = __dirname + '/data';
    var vacationPhotoDir = dataDir + '/img';
    // 如果没有对应的文件路径则,新建路径
    fs.existsSync(dataDir) || fs.mkdirSync(dataDir);
    fs.existsSync(vacationPhotoDir) || fs.mkdirSync(vacationPhotoDir);

    var path = vacationPhotoDir + '/' + files.photo.name;
    // 初始化文件的读入流和文件的输出流
    let readStream = fs.createReadStream(files.photo.path);
    let writeStream = fs.createWriteStream(path);
    readStream.pipe(writeStream);
    // 监视文件状态,end为结束状态
    readStream.on('end', () => {
      console.log('readStream end...');
    });

    res.redirect(303, "/thank-you");
  });
});

成功保存图片,这里不展示

2、场景二:获取网络图片请求,保存到本地

使用axios发送图片请求,并保存到本地

npm i axios --save

app.get("/pic", function(req, res) {
  let imgurl = 'https://cn.bing.com/th?id=OIP.YEswNYElwwyakflqCkrPawAAAA&pid=Api&rs=';
  let path = __dirname + '/data/img';
  fs.existsSync(path) || fs.mkdirSync(path);
  // request(url).pipe(fs.createWriteStream(path));
  axios({
    method: 'get',
    url: imgurl,
    responseType: 'stream'
  })
  .then((response) => {
    let writeStream = fs.createWriteStream(path+'/b.png');
    writeStream.on('close',function(){
      console.log('write close...')
    })
    response.data.pipe(writeStream);
  })
  .catch(error => {
    console.log(error)
  })
  res.send("OK");
});
posted @ 2019-09-03 21:56  mangata  阅读(235)  评论(0编辑  收藏  举报