如何将Node.js的文件上传请求转发至Tomcat(Servlet)服务器
How to Forward File Uploads from Express/HTTP Server to Tomcat
Alright, let's get that file upload forwarding sorted out. The key thing here is that you need to wait for the form to finish parsing before you can forward the file, and use the request module to construct a proper multipart/form-data request to send to Tomcat. Here's how to adjust your code to make it work:
var http = require('http'); var request = require('request'); var formidable = require('formidable'); var fs = require('fs'); // Set up your HTTP server (integrates with Express if you're using it) http.createServer(function(req, res) { // Handle only POST requests to your upload endpoint if (req.url === '/upload' && req.method.toLowerCase() === 'post') { var form = new formidable.IncomingForm(); const tomcatTargetUrl = 'http://localhost:8080/fileHandler'; // Replace with your actual Tomcat endpoint // Parse the incoming form data (including the file) form.parse(req, function(err, fields, files) { // Handle parsing errors first if (err) { console.error('Failed to parse incoming form:', err); res.statusCode = 500; res.end('Error processing your upload'); return; } const uploadedFile = files.fileToUpload; console.log('Received file to forward:', uploadedFile.name); // Construct and send the request to Tomcat request.post({ url: tomcatTargetUrl, formData: { // Match the field name your Tomcat endpoint expects (same as the frontend uses) fileToUpload: { value: fs.createReadStream(uploadedFile.path), options: { filename: uploadedFile.name, // Preserve original filename contentType: uploadedFile.type // Preserve original content type } }, // Forward any additional form fields if needed ...fields } }, function(forwardErr, tomcatResponse, tomcatBody) { // Handle errors during forwarding if (forwardErr) { console.error('Failed to forward request to Tomcat:', forwardErr); res.statusCode = 500; res.end('Failed to forward your upload'); return; } // Pass Tomcat's response back to the original client res.statusCode = tomcatResponse.statusCode; res.end(tomcatBody); // Clean up the temporary file created by formidable (optional but recommended) fs.unlink(uploadedFile.path, (unlinkErr) => { if (unlinkErr) console.error('Error deleting temporary file:', unlinkErr); }); }); }); return; } // Handle non-upload requests res.statusCode = 404; res.end('Endpoint not found'); }).listen(3000, function() { console.log('Server running on port 3000 - ready to handle uploads'); });
Key Notes to Keep in Mind:
- Async Parsing: Always put your forwarding logic inside the
form.parsecallback—formidable parses the form asynchronously, so you can't access the file data before this callback runs. - Stream the File: Using
fs.createReadStreaminstead of reading the entire file into memory is more efficient, especially for large files. - Preserve File Metadata: Make sure to pass along the original filename and content type so Tomcat processes the file correctly.
- Error Handling: Don't skip error handling for form parsing and forwarding—this ensures you can debug issues and give meaningful feedback to the client.
- Clean Up: Formidable stores uploaded files in a temporary directory; deleting them after forwarding prevents unnecessary disk usage.
内容的提问来源于stack exchange,提问作者shashidhar
相关产品推荐
相关产品推荐

