当前位置:网站首页>Express file download
Express file download
2022-06-30 09:16:00 【The man of Jike will never admit defeat】
Express の File download
Last one Talking about using express Handle POST request .
File download
Simple and crude , Just download the file res.download() Method .( This method can only be used in v4.16.0 Then use …)
app.get('/download/:type', (req, res) => {
let type = req.params.type || '';
console.log(type);
if (type === 'pdf') {
res.download('C:/Users/lenovo/Desktop/if.pdf');
} else if (type === 'image') {
res.download('C:/Users/lenovo/Pictures/love.jpg');
} else {
res.download('../resource/index.html');
}
});

There are several points to pay attention to
- Either absolute path or relative path is OK . This is different
res.sendFile()Method , The latter can only use absolute paths . - windows The following directory separator is
\, But here we use/
This method actually has other parameters , For example, specify the file name to download .
app.get('/download/:type', (req, res) => {
let type = req.params.type || '';
console.log(type);
if (type === 'pdf') {
res.download('C:/Users/lenovo/Desktop/if.pdf', ' If .pdf');
} else if (type === 'image') {
res.download('C:/Users/lenovo/Pictures/love.jpg', ' Love .jpg');
} else {
res.download('../resource/index.html', ' home page .html');
}
});

If the code does not take effect , Try disabling caching in your browser …( Don't ask me how I know )
Come again , Is to specify the callback function when the transfer is completed or an exception occurs
app.get('/download/:type', (req, res) => {
let type = req.params.type || '';
console.log(type);
if (type === 'pdf') {
res.download('C:/Users/lenovo/Desktop/if.pdf', ' If .pdf');
} else if (type === 'image') {
// Callback function
res.download('C:/Users/lenovo/Pictures/love.jpg', ' Love .jpg', (err) => {
if (err) {
console.log(' Error downloading content ', err);
} else {
console.log(' Transmission complete ');
}
});
} else {
res.download('../resource/index.html', ' home page .html');
}
});
No, v4.16.0 What do I do ???
Man, I advise you to upgrade earlier …( dog's head
Actually download Methodical Official documents , The author makes it clear ,download For internal use res.sendFile() Realized , The latter from v4.8.0 Supported by , If you even v4.8.0 either , I heard that next door SpringBoot Still supporting Java 8, Um. ~ o( ̄▽ ̄)o
res.sendFile() Automatically set according to the file extension Content-Type Response head . Let's try to send the file using the absolute file path above .
app.get('/file1', (req, res) => {
res.sendFile('C:/Users/lenovo/Pictures/love.jpg');
});
The effect is that the picture is displayed directly in the browser window 
Why? We'll talk about it later . There is a question worth thinking about , If we provide many different interfaces for downloading files , These files are represented by absolute paths , It's hard to maintain , Because there are many changes . therefore sendFile() The other second parameter is provided options.
res.sendFile(path [, options] [, fn])
options Represents an object , One of them root attribute . If the function is called without root Then you have to path In the form of an absolute path ; If you specify root that path You can use relative paths ,express Will help us parse the final location of the file . The whole directory is like this 
app.get('/file2', (req, res) => {
console.log(__dirname); // C:\Users\lenovo\Desktop\css\node\express
let options = {
root: path.join(__dirname, '../resource')
};
res.sendFile('love.jpg', options);
});
First __dirname yes Node.js Present in China js Representation of the absolute path of the file . In the code we use path The root path of the core library splicing download file path.join(__dirname, '../resource'). Actually … I didn't write that for the first time …
app.get('/file3', (req, res) => {
console.log(__dirname); // C:\Users\lenovo\Desktop\css\node\express
let options = {
root: path.join(__dirname, 'resource')
};
res.sendFile('../resource/love.jpg', options);
});
This will give you an error ForbiddenError: Forbidden, Although the official website really says that relative paths can be used, including ..( Although I overturned , But it's really not a lie )
Now let's talk about , Why use sentFile() The file is displayed directly in the window , Instead of downloading ?
Content negotiation
Content negotiation I think it is a big content , To tell you the truth, before studying the above question , I have no idea what content negotiation is for , In the future, I will never say that I want to turn to the front …
stay HTTP Agreement , Content negotiation is such a mechanism , Pass for the same URI The resources pointed to provide different presentation forms , It can enable the user agent to select the best match to meet the user's needs . – MDN Official website
In human terms , It can be simply understood as , If the browser passes URL Ask for a paragraph of text , The server returns English to the English user , Return Chinese... To Chinese users , Such a network resource ( written words ) It only corresponds to one URL. Why is the server so smart ? That's because the browser sends a series of... When it requests Accept Request header for ; How do browsers know whether it is English or Chinese ? That's because the response consists of a series of Content Response header for .( The following figure comes from MDN Official website )
Let's take the example above , The picture is not downloaded directly but displayed in the window , Is the response header Content-Disposition The devil of it
Content-Disposition Tell the browser how to display the content returned to you
inline: As part of the web page, it is directly displayed in the browser ( Default )attachment: As The attachment Direct download . You can add; filename=Specify the name of the downloaded file .
Because the default attribute is inline, So the picture directly shows , Is this function a little familiar , you 're right , Generally, the browser will right-click the image and it will appear Open the picture in the new tab The option to … You can do this 

Then let's modify the code , You can use sendFile() Download the file .
app.get('/file4', (req, res) => {
res.setHeader('Content-Type', 'image/jpeg');
// res.setHeader('Content-Disposition', 'inline');
res.setHeader('Content-Disposition', 'attachment; filename="loveBySendFile.jpg"');
res.sendFile('C:/Users/lenovo/Pictures/love.jpg');
});

Okay , That's all for downloading files , It is inexplicably efficient to study at home during the National Day holiday , Happy holidays ( Don't ask me why I use it for a while Edge, For a while Google browser , I'll use it later FireFox, The question is that I have Opera It's no use , It's actually a bad screenshot , Especially the download file section .
边栏推荐
- ES6 learning road 5 symbol
- CUDA implements matrix replication
- Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
- Common query and aggregation of ES
- JVM调优相关命令以及解释
- Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
- ES6 learning path (IV) operator extension
- Detectron2 source code reading 3-- encapsulating dataset with mapper
- Concatapter tutorial
- 100 lines of code and a voice conversation assistant
猜你喜欢

Deep understanding of kotlin collaboration context coroutinecontext

9.JNI_ Necessary optimization design

C accesses mongodb and performs CRUD operations

Explanation on the use of password profiteering cracking tool Hydra

Talk about the job experience of kotlin cooperation process

Detailed explanation of pytoch's scatter function

Raspberry pie 4B no screen installation system and networking using VNC wireless projection function

Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)

Set, map and modularity

Resnet50+fpn for mmdet line by line code interpretation
随机推荐
[protobuf] protobuf generates cc/h file through proto file
What kind of experience is it to develop a "grandson" who will call himself "Grandpa"?
C # get the current timestamp
Abstract factory pattern
14岁懂社会-《关于“工作的幸福”这件事儿》读书笔记
Opencv learning notes -day 11 (split() channel separation function and merge() channel merge function)
Flink sql -- No factory implements ‘org. apache. flink. table. delegation. ExecutorFactory‘.
Esp32 things (I): Preface
Occasionally, Flink data is overstocked, resulting in checkpoint failure
Introduction to MySQL basics day4 power node [Lao Du] class notes
Unsupportedclassversionerror is reported when starting jar package. How to repair it
Opencv learning notes -day3 (mat object and creation related operations mat:: clone(), mat:: copyto(), mat:: zeros(), mat:: ones(), scalar()...)
Esp32 things (V): analysis of common API of esp32 of Swiss Army knife
Flink Sql -- toAppendStream doesn‘t support consuming update and delete changes which
Detectron2 source code reading 4-- registrar construction model
Deep Learning with Pytorch- neural network
Deep Learning with Pytorch- A 60 Minute Blitz
Deeply understand the working principle of kotlin collaboration suspend (beginners can also understand it)
Mmdet line by line code interpretation of positive and negative sample sampler
Using appbarlayout to realize secondary ceiling function