好吧,所以我已经尝试过使用连接形式,但由于某些原因我无法让它工作,但我想我应该理解这是如何从头开始半无论如何.
我不明白我上传的multipart / formdata文件的位置,或者当我的应用程序发布到网址时如何在我的应用程序中访问它. – 我喜欢直接访问文件数据,并使用节点fs模块写入文件输出. – 例如:
app.post('/testy',function(req,res){ console.log(req.body); console.log(req.headers); res.redirect('back'); }); app.get('/testy',res){ res.send('<form method="post" action="/testy" enctype="multipart/form-data">' + '<p>Image: <input type="file" name="test" /></p>' + '<p><input type="submit" value="Upload" /></p>' + '</form>'); });
因此,实际记录的唯一req var是req标头,body是空的. (可能应该是我理解的).但我得到的是文件数据在哪里?寻找我想的$_FILES数组的PHP等价物. – 这是我记录的标题.
'accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8','accept-language': 'en-us,en;q=0.5','accept-encoding': 'gzip,deflate','accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7','keep-alive': '115',connection: 'keep-alive',referer: 'http://127.0.0.1:3000/testy',cookie: 'connect.sid=lDRpluTxjUJeuTmkXlybrYeZ.JYTB155s2DGce2dsyfv1Op5ISCY8uqyqJZK8NjlZ5jM; socketio=flashsocket','x-insight': 'activate','content-type': 'multipart/form-data; boundary=---------------------------5856401949371863571646035001','content-length': '30128' }
任何关于我失踪的东西都会被人们所喜爱!
解决方法
这是非常详细的没有连接形式的版本.正如您所看到的,这不是有效的,而是试图对其工作方式发挥指导作用.
var express = require('express'),fs = require('fs'); app = express.createServer(); app.post('/testy',res){ var body = ''; var header = ''; var content_type = req.headers['content-type']; var boundary = content_type.split('; ')[1].split('=')[1]; var content_length = parseInt(req.headers['content-length']); var headerFlag = true; var filename = 'dummy.bin'; var filenameRegexp = /filename="(.*)"/m; console.log('content-type: ' + content_type); console.log('boundary: ' + boundary); console.log('content-length: ' + content_length); req.on('data',function(raw) { console.log('received data length: ' + raw.length); var i = 0; while (i < raw.length) if (headerFlag) { var chars = raw.slice(i,i+4).toString(); if (chars === '\r\n\r\n') { headerFlag = false; header = raw.slice(0,i+4).toString(); console.log('header length: ' + header.length); console.log('header: '); console.log(header); i = i + 4; // get the filename var result = filenameRegexp.exec(header); if (result[1]) { filename = result[1]; } console.log('filename: ' + filename); console.log('header done'); } else { i += 1; } } else { // parsing body including footer body += raw.toString('binary',i,raw.length); i = raw.length; console.log('actual file size: ' + body.length); } }); req.on('end',function() { // removing footer '\r\n'--boundary--\r\n' = (boundary.length + 8) body = body.slice(0,body.length - (boundary.length + 8)) console.log('final file size: ' + body.length); fs.writeFileSync('files/' + filename,body,'binary'); console.log('done'); res.redirect('back'); }) }); app.get('/testy',res){ res.send('<form method="post" action="/testy" enctype="multipart/form-data">' + '<p>Image: <input type="file" name="test" /></p>' + '<p><input type="submit" value="Upload" /></p>' + '</form>'); }); app.listen(4000);