background
Implements the service of uploading a file to NodeJS.
The introduction of
const fs = require('fs');
const path = require('path');
const extname = path.extname;
const os = require('os');
Copy the code
Import these packages first.
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('/'); });Copy the code
As you can see, ctx.request.files.file gets the files from the HTTP request and builds the file stream to write to the local file.
My code example
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 = 'Error: uploaded file missing '; 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(' Uploaded successfully! '); } let newPath = path.join(ctx.projectRootPath, '/public',uploadedFileName); fs.renameSync(targetFile, newPath); If (fs.existssync (newPath)){console.log(' Moved file successfully to ${newPath} '); } ctx.response.type = 'application/json'; ctx.body = {resultCode:200, message:'ok'} } module.exports = function (){ return upload; };Copy the code
Console access:
Curl http://127.0.0.1:6601/upload - F "file = @ / Users/zhangyunfei/Downloads / 1. TXT" - "source = XXX" F - vCopy the code
Curl curl curl curl curl curl curl
reference
Github.com/koajs/examp…