背景
实现上传一个文件到 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 实现上传调用
网友评论