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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 文件上传需要解析文件,之前我们解析数据使用body-parser,解析文件可以用multer。body-parse...
    super静_jingjing阅读 4,553评论 0 1
  • 前端页面结构 node 服务端 需用到connect-multiparty 模块 npm install conn...
    希硕阅读 5,687评论 0 0
  • 今早窗外叽叽喳喳的鸟鸣叫醒了我,由于已经连续十天在闹钟前起床,今天虽然比往常早了一个小时,不过还是决定起床。 悠哉...
    许小糊阅读 1,337评论 0 6
  • 今天入党培训结束了,感觉收获很大。第二次参加培训,重听了一次党课,对党的历史党的章程,党的纪律,党的要求都有了更深...
    清风如水阅读 3,328评论 0 4
  • rpc服务设计 经验:http://www.infoq.com/cn/presentations/system-s...
    jey恒阅读 6,243评论 0 3

友情链接更多精彩内容