gpt4 book ai didi

node.js - 如何使用 angular-file-upload 在 Node.js Express 应用程序中获取上传的文件

转载 作者:搜寻专家 更新时间:2023-10-31 23:13:09 24 4
gpt4 key购买 nike

我想使用 angular-file-upload 上传文件。但是当我尝试访问 req.body.filesreq.files 时,我得到了 undefined

谁能告诉我如何在 node.js express 应用程序中获取通过 angular-file-upload 上传的文件?

请求负载如下:

Content-Disposition: form-data; name="myFile"; filename="BroadcomLogo.gif"
Content-Type: image/gif

JS代码:

$scope.upload[index] = $upload.upload({
url : '/upload',
method: 'POST',
file: $scope.selectedFiles[index],
fileFormDataName: 'myFile'
});

Node 代码

upload: function(req, res) {
console.log(req.files);
res.send("Hello");
},

最佳答案

您需要使用一个中间件来解析来自 Node.js 请求的文件:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.post('/upload', multipartMiddleware,upload);

Simply put, middleware are functions that handle requests. A server created by connect.createServer can have a stack of middleware associated with it. When a request comes in, it is passed off to the first middleware function, along with a wrapped ServerResponse object and a next callback. Each middleware can decide to respond by calling methods on the response object, and/or pass the request off to the next layer in the stack by calling next().

http://stephensugden.com/middleware_guide/

对于多部分中间件,它将调用 next() 方法,因此您可以编写自己的函数来响应请求。

当然需要先安装:npm install connect-multiparty

它们是处理分段上传的其他中间件:

你可能应该使用与 connect 兼容的,因为 express 是建立在 connect 之上的

关于node.js - 如何使用 angular-file-upload 在 Node.js Express 应用程序中获取上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24610996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com