File upload and forward using egg.js + superagent
//App/controller/file.jsConstController= require(' Egg ').Controller;ConstFs= require(' FS ')ConstRequest= require(' superagent ')ConstSendtowormhole= require(' Stream-wormhole ')ConstToArray= require(' Stream-to-array ');ConstPath= require(' path ');ConstUuid= require(' Uuid/v1 ');classFilecontrollerextendsController{Asyncfile(){ Const {CTx,App} = This; //Get uploaded files LetStream; Try {Stream=AwaitCTX.GetFileStream(); } Catch(e){ Console.Error(' file not present or file error '); } if(!Stream{ CTX.Throw(403,' file not present or file error ')return false; } ConstNameID= UUID().Replace(/-/g, ''); ConstFileName=NameID+ '.' + Stream.filename.toLowerCase().Split('.').Pop(); //file temporarily exists under the App/public folder ConstTarget= Path.Join( This.Config.BaseDir, ' App/public ',FileName; ConstUrl= ' upload address '; //upload using superagent Try { //Convert stream ConstParts=AwaitToArray(stream); LetBuf= Buffer.concat(parts); //write file save to local FS.Writefilesync(Target,Buf; //Upload ConstRes=Await request.Post(URL).Attach(' file ',Target,FileNameCTX.Body = Res.text; } Catch(ERR){ //The uploaded file stream must be consumed or the browser response will be jammedAwaitSendtowormhole(stream); CTX.Throw( -,' Error on file '); } //Because only temporary save, delete the file after the upload is complete FS.unlink(Target, function(ERR){ if(!Err{ Console.Log(' file deleted: ',Target; } }); }}Module.exports =Filecontroller;
Address Resource Links
Superagent Official documents
http://visionmedia.github.io/superagent/
Egg File Upload Reference document
Https://eggjs.org/zh-cn/basics/controller.html#%E8%8E%B7%E5%8F%96%E4%B8%8A%E4%BC%A0%E7%9A%84%E6%96%87%E4%BB%B6
Node egg.js using superagent to do file forwarding