NodeJS 实现文件上传

背景

实现上传一个文件到 NodeJS 的服务。

引入

  const fs = require('fs');
  const path = require('path');
  const extname = path.extname;
  const os = require('os');

先导入这些包。

  app.use(async function(ctx, next) {
  // ignore non-POSTs
  if ('POST' != ctx.method) return await next();

  const file = ctx.request.files.file;
  const reader = fs.createReadStream(file.path);
  const stream = fs.createWriteStream(path.join(os.tmpdir(), Math.random().toString()));
  reader.pipe(stream);
  console.log('uploading %s -> %s', file.name, stream.path);

  ctx.redirect('/');
});

可以看到,通过 ctx.request.files.file 获得来自http请求中的文件,再构建文件流写入到本地文件。

我的代码示例

  const fs = require('fs');
  const path = require('path');
  const extname = path.extname;
  const os = require('os');

  const upload = async function(ctx, next) {
    // ignore non-POSTs
    if ('POST' != ctx.method) return await next();
    if(!ctx.path.indexOf('/upload') == 0 )  return await next();

    const paras = ctx.request.body;
    console.log('paras = ' + JSON.stringify(paras));
    if(!ctx.request.files.file){
      const err = '参数错误: 缺少上传的文件';
      console.log(err);
      ctx.body = {resultCode:400, message:err}
      ctx.response.type = 'application/json';
      return;
    }
    let uploadedFileName = ctx.request.files.file.name;
    console.log(`ctx.request.files.file.name = ${uploadedFileName}`);
    const file = ctx.request.files.file;
    const reader = fs.createReadStream(file.path);
    let targetFile = path.join(os.tmpdir(), Math.random().toString());
    console.log(`targetFile = ${targetFile}`);
    const stream = fs.createWriteStream(targetFile);
    reader.pipe(stream);
    console.log('uploading %s -> %s', file.name, stream.path);
    if(fs.existsSync(targetFile)){
      console.log('上传成功!');
    }
    let newPath = path.join(ctx.projectRootPath, '/public',uploadedFileName);
    fs.renameSync(targetFile, newPath);
    if(fs.existsSync(newPath)){
      console.log(`移动文件成功,到 ${newPath} `);
    }
    ctx.response.type = 'application/json';
    ctx.body = {resultCode:200, message:'ok'}
  }



  module.exports = function (){
    return upload;
  };

控制台访问:

curl http://127.0.0.1:6601/upload -F   "file=@/Users/zhangyunfei/Downloads/1.txt" -F "source=xxx" -v

使用 curl 实现上传调用

参考

https://github.com/koajs/examples/blob/master/upload/app.js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值