简体   繁体   English

从客户端 Node.js 下载文件

[英]Downloading File From Client Side Node.js

so I am trying to build a website that allows users to download files that are located in the server computer when the users access the website and click a download button.所以我正在尝试建立一个网站,当用户访问该网站并单击下载按钮时,该网站允许用户下载位于服务器计算机中的文件。

I wish to use as few libraries as possible due to some real world limitations.由于一些现实世界的限制,我希望使用尽可能少的库。 Ideally no Express or Ajax.理想情况下没有 Express 或 Ajax。 And I think it should be fully possible with just vanilla node.js而且我认为仅使用 vanilla node.js 就应该完全有可能

From my search on the internet it seems most of the code is of this form:从我在互联网上的搜索来看,似乎大部分代码都是这种形式:

 const fs = require('fs'); const https = require('https'); // URL of the image const url = 'GFG.jpeg'; https.get(url,(res) => { // Image will be stored at this path const path = `${__dirname}/files/img.jpeg`; const filePath = fs.createWriteStream(path); res.pipe(filePath); filePath.on('finish',() => { filePath.close(); console.log('Download Completed'); }) })

However, the code doesn't seem to be doing what I want.但是,代码似乎没有做我想要的。 First, it requires an url, so it is more about directing a resource online to another location.首先,它需要一个 url,因此它更多的是关于将在线资源定向到另一个位置。 Whereas I want to actually serve a locally stored file on the server to users when they access the website.而我想在用户访问网站时实际向用户提供服务器上本地存储的文件。

Second, it appears to be downloading to the server computer.其次,它似乎正在下载到服务器计算机。 But what I want is to let users download to their own client devices.但我想要的是让用户下载到他们自己的客户端设备。 Basically the normal download function you would encounter when you want to download something on the Internet and you see your browser's "Download" section having some new entries.基本上,当您想在 Internet 上下载某些内容并且您会看到浏览器的“下载”部分有一些新条目时,您会遇到正常的下载功能。

How can I achieve what I want?我怎样才能达到我想要的?

I'm a total noob at this, so it would be great if I can get a skeleton code with some dummy file or pathname.我对此完全是个菜鸟,所以如果我能得到一个带有一些虚拟文件或路径名的骨架代码,那就太好了。

Appreciate any guidance.感谢任何指导。 Thanks!谢谢!

You are missing an http.server.您缺少 http.server。 http.get just does a web request and as you said you don't want to do that. http.get 只是做一个网络请求,正如你所说,你不想这样做。

Here is some example code creating a server and serving a single file without using express:下面是一些示例代码,它创建了一个服务器并在不使用 express 的情况下提供了一个文件:

const fs = require('fs');
const path = require('path');
const http = require('http');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, '/files/img.jpeg');

    response.writeHead(200);

    var readStream = fs.createReadStream(filePath);
    readStream.pipe(response);
}).listen(2000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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