[英]Pass data from res.write() to formidable filename
I use node to allow users to upload a file: 我使用节点允许用户上传文件:
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
http.createServer(function (req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = 'team_1_uploads/' + files.filetoupload.name + files.filetoupload.token;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write(' FILE UPLOADED!');
res.end();
});
});
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<div align="center">');
res.write('<html>');
res.write('<body>');
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input id="file_input" type="file" name="filetoupload" style="margin-left: 100px; margin-bottom: 10px; color: transparent"><br>');
res.write('<input id="submit_button" type="submit">');
res.write('</form>');
res.write('</body>');
res.write('</html>');
res.write('</div>');
return res.end();
}
}).listen(3131);
As you can see, I am trying to append a token onto the filename. 如您所见,我正在尝试将令牌附加到文件名上。 The upload button gets served by node through an iframe on the front-end. 节点通过前端的iframe为上载按钮提供服务。 I can pass the token to res.write() using postMessage, by adding the following script to res.write(): 通过将以下脚本添加到res.write(),我可以使用postMessage将令牌传递给res.write():
res.write("<script>window.addEventListener('message', function(event) { document.getElementById('file_input').dataset.token = event.data; global_hold_token = event.data; })</script>");
This sets the token to the form element by using the data attribute on the form element. 这通过使用form元素上的data属性将令牌设置为form元素。 The message is received from the front end by using postMessage: 使用postMessage从前端接收消息:
$('#my_frame')[0].contentWindow.postMessage(token, '*')
I thought I could then parse the data attribute using formidable . 我以为可以再使用formidable解析data属性 。 But node doesn't seem able to access the data attribute on the form element, even though it can access the name. 但是节点似乎无法访问form元素上的data属性,即使它可以访问名称。
The ?token=xxxxxx
is a GET parameter. ?token=xxxxxx
是GET参数。 You can get these from the req
object, under the req.query
object 您可以从req.query
对象下的req
对象获得这些
http://expressjs.com/en/api.html#req.query http://expressjs.com/en/api.html#req.query
So in your case, it will be in req.query.token
因此,在您的情况下,它将位于req.query.token
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.