Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
756 views
in Technique[技术] by (71.8m points)

node.js - How to upload a file using Node JS function in Azure

I am trying to create an Azure function that handles file upload. I have tried different options (trying to read from request directly or using formidable).

For both these cases I am getting following error when the function is executed.

Exception while executing function: Functions.UploadFile. mscorlib: TypeError: req.on is not a function  
    at IncomingForm.parse (D:homesitewwwroot
ode_modulesformidablelibincoming_form.js:117:6)  
    at module.exports (D:homesitewwwrootUploadFileindex.js:5:10)  
    at D:Program Files (x86)SiteExtensionsFunctions1.0.11702inazurefunctionsfunctions.js:106:24.  

The function code is as below

var formidable = require("formidable");  

module.exports = function (context, request) {  
    context.log('JavaScript HTTP trigger function processed a request.');      
    var form = new formidable.IncomingForm();  
    form.parse(request, function (err, fields, files) {  
        context.res = { body : "uploaded"};  
    });  
    context.done();  
};  

Any help is appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got it to work with following. Request object is neither a Stream nor an EventEmitter in Azure functions (and in AWS lambda too). It just has body and headers populated. I took help from https://www.npmjs.com/package/parse-multipart. I had to tune it for Azure functions

var multipart = require("parse-multipart");

module.exports = function (context, request) {  
    context.log('JavaScript HTTP trigger function processed a request.'); 
    // encode body to base64 string
    var bodyBuffer = Buffer.from(request.body);
    // get boundary for multipart data e.g. ------WebKitFormBoundaryDtbT5UpPj83kllfw
    var boundary = multipart.getBoundary(request.headers['content-type']);
    // parse the body
    var parts = multipart.Parse(bodyBuffer, boundary);
    context.res = { body : { name : parts[0].filename, type: parts[0].type, data: parts[0].data.length}}; 
    context.done();  
};

This seems to work better with Azure Function 2.x runtime (beta). I have updated the code. I have tested this with PDF, JPG, PNG and XLSX.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...