微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Node JS 中从我自己的服务器下载文件?

如何解决如何在 Node JS 中从我自己的服务器下载文件?

嗨,我正在学习 Node JS,到目前为止我已经创建了一个上传到服务器的文件,之后我想下载我的文件,但使用 GET url 像 localhost:8080/myfile.html?name=test.txt,myfile.txt 。 html只有一个提交按钮可以从我的电脑上传任何文件,test.txt是我上传到我的服务器上的那个文件

var http = require('http');
var url = require('url');
var path = require('path')
var formidable = require('formidable');
var fs = require('fs');

http.createServer(function (req,res) {
  const queryObject = url.parse(req.url,true).search;
  if (req.url == '/fileupload') {
    var form = new formidable.IncomingForm();
    form.parse(req,function (err,fields,files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/pcname/Desktop/' + files.filetoupload.name;
      console.log(files.filetoupload.name);
      fs.rename(oldpath,newpath,function (err) {
        if (err) throw err;
        res.write('<p>File uploaded and moved!</p><br>');
        res.write('You can check your file here: ' + newpath)
        res.end();
      });
 });
  } else {
    fs.readFile('test.html',function(err,data) {
        res.writeHead(200,{'Content-Type': 'text/html'});
        res.write(data);
        return res.end();
      });
    if (queryObject == '?name=' + files.filetoupload.name)
      {
        http.get(url,function(response){
          const filename = path.basename(url);
          const fileStream = fs.createWriteStream(filename)
          response.pipe(fileStream);
      
          fileStream.on("error",function(err){
            console.log("Error writing to the stream");
            console.log(err);
          });
          fileStream.on("finish",function(){
            fileStream.close();
            console.log("Done!");
          });
        });
      }
  }
}).listen(8080); 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。