简体   繁体   English

您可以使用 RESTApi 从服务器下载文件吗

[英]Can you download files from a server with RESTApi

I was wondering if you can call create a GET request on a RESTApi server to download a file.我想知道您是否可以在 RESTApi 服务器上调用创建 GET 请求来下载文件。 For example if i called a GET request to http://<IP>/storage/download/:filePath/ it would download that file.例如,如果我向http://<IP>/storage/download/:filePath/调用GET请求,它将下载该文件。 I am writing the RESTAPi in nodejs.我正在用 nodejs 编写 RESTAPi。

 const express = require('express'); const router = express.Router(); const fs = require('fs'); const path = require('path'); const root = {} //for this example say filepath = api%2Fstorage%2FImages%2FtestPhoto.png or api/storage/Images/testPhoto.png router.get("/download/:filePath", (req, res, next) => { var filePath = req.params.filePath; filePath = decodeURIComponent(filePath) res.sendFile(filePath); // this is what im questioning. If i use this will it send the file? if so how will i download it on the front end? })

Yes.是的。 If the server directory is this如果服务器目录是这个

main.js
 └── storage
      └── Image
           └── testPhoto.png

Add this,添加这个,

router.use('/api/storage', express.static('storage'));

Then request it from frontend.然后从前端请求它。 GET /api/storage/Image/testPhoto.png获取 /api/storage/Image/testPhoto.png

Express has a helper for this to make life easier. Express为此提供了帮助,使生活更轻松。

app.get('/download', function(req, res){
  const file = `${__dirname}/folder/download.csv`;
  res.download(file); // Set disposition and send it.
});

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

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