我想在我的app.js服务器上传一个文件,该文件应该将该文件传输到像我的upload.js服务器这样的跨域服务器.
upload.js服务器正在运行.我的问题是app.js服务器.请求似乎能够传输文件(https://github.com/request/request#streaming).但是我不懂它.
我总是得到:我的app.js中的[错误:协议无效]
最重要的是这条线:
fs.createReadStream(file.path).pipe(request.post('localhost:4000/upload'))
我将post更改为put并在我的upload.js中post方法也放,但它会导致相同的错误.
我的目标是将文件从html页面上传到localhost:3000 / upload,将文件管道传输到localhost:4000 / upload(理想情况下使用相同的文件名).但我没有得到它的工作(这post没有帮助我).
app.js:
var express = require('express'),multiparty = require('multiparty'),request = require('request'),fs = require('fs'),util = require('util'),http = require('http'); var app = express(); app.use('/static',express.static('static')); process.on('uncaughtException',function (err) { console.log(err); }); app.get('/',function (req,res) { res.redirect('static/index.html'); }); app.post('/upload',function(req,res,next){ //https://github.com/request/request#streaming var form = new multiparty.Form(); form.parse(req,function(err,fields,files) { res.writeHead(200,{'content-type': 'text/plain'}); res.write('received upload:\n\n'); res.end(util.inspect({fields: fields,files: files})); }); form.on('file',function(name,file) { //stream it to localhost:4000 with same name fs.createReadStream(file.path).pipe(request.post('localhost:4000/upload')) console.log(file.path); }); }); var server = app.listen(3000,'0.0.0.0',function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s',host,port); });
index.html的:
<!DOCTYPE html> <html> <head lang="en"> <Meta charset="UTF-8"> <title>Upload</title> </head> <body> <h2>Upload</h2> <form method="post" action="/upload" enctype="multipart/form-data"> <input type="file" id="file" name="file" /> <button>upload</button> </form> </body> </html>
upload.js:
var express = require('express'),cors = require('cors'),app = express(); app.use(cors()); process.on('uncaughtException',cors(),next){ res.json({msg: 'This is CORS-enabled for all origins!'}); }); app.post('/upload',next){ var form = new multiparty.Form(); form.parse(req,file) { console.log(file); console.log(name); }); }); app.listen(4000,function(){ console.log('CORS-enabled web server listening on port 4000'); });
解决方法
更新
我相信你错过了网址上的协议.
它应该工作,如果你将http协议添加到网址:
fs.createReadStream(file.path).pipe(request.post('http://localhost:4000/upload'))
使上传工作
将文件内容传递给upload.js中的POST函数时,多部分表单数据将丢失.您需要创建一个新的POST请求并传递原始文件内容.
在app.js中执行以下操作:
form.on('file',file) { var formData = { file: { value: fs.createReadStream(file.path),options: { filename: file.originalFilename } } }; // Post the file to the upload server request.post({url: 'http://localhost:4000/upload',formData: formData}); }
这也将传递原始文件名.
有关更多信息,请参阅:https://github.com/request/request#multipartform-data-multipart-form-uploads
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。