如何在Azure中使用Node JS功能上传文件 [英] How to upload a file using Node JS function in Azure

查看:96
本文介绍了如何在Azure中使用Node JS功能上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个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:\home\site\wwwroot\node_modules\formidable\lib\incoming_form.js:117:6)  
    at module.exports (D:\home\site\wwwroot\UploadFile\index.js:5:10)  
    at D:\Program Files (x86)\SiteExtensions\Functions\1.0.11702\bin\azurefunctions\functions.js:106:24.  

功能代码如下

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();  
};  

感谢您的帮助.

推荐答案

我了解了以下内容.在Azure函数中(以及在AWS lambda中),请求对象既不是Stream也不是EventEmitter.它只是具有正文和标头填充.我从 https://www.npmjs.com/package/parse-multipart.我必须针对Azure功能进行调整

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();  
};

这似乎与Azure Function 2.x运行时(测试版)更好地配合.我已经更新了代码.我已经用PDF,JPG,PNG和XLSX对此进行了测试.

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.

这篇关于如何在Azure中使用Node JS功能上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆