简体   繁体   中英

Uploading files with node js and express

I'm trying to upload a .mp3 file to the node server in my local. I've followed 2 approaches for this:

  1. Using uploadit.js as a separate file - in this,

 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 = './audio/audio.mp3'; fs.readFile(oldpath, function(err, data){ if(err) throw err; fs.writeFile(newpath, data, function(err){ if(err) throw err; res.write('<center>File uplaoded and saved</center>'); res.end(); }); fs.unlink(oldpath, function(err){ if(err) throw err; }); }); }); } else{ res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<div><form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit" >'); res.write('</form></div>'); return res.end(); } }).listen(4200); 

It launches the app in 4200 port and is available.

  1. In Approach 2, I was trying to avoid the creation of a new port (as it is not possible when launched in env. like Heroku to access the PORT). So I tried integrating the code in the another file when it downloads the file content

 var express = require('express'); var app = express(); var server = require('http').Server(app); var fs = require('fs'); var io = require('socket.io')(server); var ss = require('socket.io-stream'); app.use(express.static(`${__dirname}/html`)); server.listen('5001'); app.get('/uploadform', 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 = './audio/audio.mp3'; fs.readFile(oldpath, function(err, data){ if(err) throw err; fs.writeFile(newpath, data, function(err){ if(err) throw err; res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<center>File uplaoded and saved</center>'); res.end(); }); fs.unlink(oldpath, function(err){ if(err) throw err; }); }); }); } else{ res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<div'> res.write('<form action="fileupload" method="post" enctype="multipart/form-data">'); res.write('<input type="file" name="filetoupload"><br>'); res.write('<input type="submit"'); res.write('</form></div>'); return res.end(); } }); 

Here, when I select the file and hit the submit button, it is taking me to an error page with 404 status as below:

在此处输入图片说明

Tried my known possible ways, but still needed help on how to resolve this issue and upload the file smoothly.

Thanks in advance.

Basically what you are saying in your code is 'when there is a get request to '/uploadform' then call the function' and then within the function you are saying if the req.url is "/fileupload" do the underlying job. how can the req.url be equal to '/uploadform' and also equal to "/fileupload" at the same time.i think the best way to do it would be

var express = require('express');
var app = express();
var server = require('http').Server(app);
var fs = require('fs');
var io = require('socket.io')(server);
var ss = require('socket.io-stream');

app.use(express.static(`${__dirname}/html`));


app.get('/uploadform', function (req, res) {

    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write('<div'>
    res.write('<form action="fileupload" method="post" enctype="multipart/form- 
    data">');
    res.write('<input type="file" name="filetoupload"><br>');
    res.write('<input type="submit"');
    res.write('</form></div>');
    return res.end();
  }); 
  app.post("/fileupload",function(req,res,next){
    var form = new formidable.IncomingForm();
    form.parse(req, function(err, fields, files){
        var oldpath = files.filetoupload.path;
        var newpath = './audio/audio.mp3';
        fs.readFile(oldpath, function(err, data){
            if(err) throw err;
            fs.writeFile(newpath, data, function(err){
                if(err) throw err;
                res.writeHead(200, {'Content-Type': 'text/html'});
                res.write('<center>File uplaoded and saved</center>');
                res.end();
            });
            fs.unlink(oldpath, function(err){
                if(err) throw err;
            });
        });
    });

});
server.listen(process.env.port||'5001');

I hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM