Home >Web Front-end >JS Tutorial >Use Node.js+Vue.js to build file compression applications
Related recommendations: "node js tutorial"
Node.js provides us with a module to assist in file compression. In this article, we will build an application where users can upload a file they want to compress and then download a compressed version of the file using the Node.js Zlib module.
To continue with this tutorial, you need to have the following qualifications:
We will start by building the backend, which is the foundation of our application.
On the desktop, create a folder for the application, name it compressor
, and set up a new Node by running npm init -y
. js project.
We write the back-end service first, so create another server
directory in the project.
Now we need to install the necessary packages for the application:
To install them all, install them in the ## Run the following command in the ##server directory:
npm i --save koa koa-router nodemon multer corsAfter completing the installation, create an
index.js file in the
server directory. This is what we will Where the backend code is written.
.gitignore file and add
node_modules to it, this will prevent the
node_modules folder from being added to git.
const express = require('express'); const multer = require('multer'); const zlib = require('zlib'); const cors = require('cors'); const fs = require('fs'); const path = require('path'); const app = express(); app.use(cors()); //multer const storage = multer.memoryStorage(); const upload = multer({ storage: storage, }); app.listen(3000, () => { console.log('App is runnuing on port 3000'); });We first ask for the packages we have installed, such as Express, Multer, and Cors. Then, we create an instance of Express and save it in a variable. We use an Express instance to configure our
cors as middleware.
zlib, which we will use to do the actual compression. We then use an instance of Express to create a server that will listen on port
3000.
gzip method.
app.post("/compress", upload.single("file"), async (req, res) => { try { const destination = `compressed/${req.file.originalname}.gz`; let fileBuffer = req.file.buffer; await zlib.gzip(fileBuffer, (err, response) => { if (err) { console.log(err); } fs.writeFile(path.join(__dirname, destination), response, (err, data) => { if (err) { console.log(err); } res.download(path.join(__dirname, destination)); }); }); } catch (err) { console.log(err); res.json(err); } });We define the
/compress route, which is a
POST request, and then pass the Multer middleware in that route. Our
Multer middleware will return the file buffer, which is stored in the
fileBuffer variable.
compressed directory and save the compressed files in it.
compressed directory.
const destination = `compressed/${req.file.originalname}.gz`;We use the Zlib method
gzip to compress the file, which takes
fileBuffer as the first parameter and then a callback function as the second parameter. The callback function consists of any possible errors and compressed responses.
compressed directory, the file will have the
.gz file extension because it is used Identifies Zlib compression.
package.lock.json file, its size is 48kb.
client directory inside the
compressor root directory. In the
client directory, create two files:
index.html and
main.js.
main.js file at the end of the body tag.
nbsp;html> <meta> <meta> <title>Vue Compressor</title> <link> <script></script> <script></script> <p> </p><h1>压缩</h1> <script></script>
对于此应用程序,用户将通过拖放添加其文件。让我们为我们的应用程序定义一个简单的用户界面。
修改模板为:
nbsp;html> <meta> <meta> <title>Vue Compressor</title> <link> <script></script> <script></script> <style> body { background: #ccc !important; } .wrapper { width: 350px; height: 350px; border: 2px dotted gray } .wrapper h4 { text-align: center; font-family: sans-serif; } </style> <p> </p><p> </p><p> </p><p> </p><p> </p><h4>在这里拖放</h4>
你可以使用任何实时服务器运行你的应用程序,这里我使用 live-server
。
我们先在 main.js
文件中定义我们的Vue.js实例。然后,我们将创建一个state来保存我们的文件。
const app = new Vue({ el: '#app', data: { files: [], loading:false }, methods: { addFile(e) { }, removeFile(file) { }, compressFile() { } } })
在Vue中实现拖放,我们需要添加一个 @drop
事件来选择我们的文件,还有一个 v-cloak
属性,这个属性用于在应用加载之前隐藏 {{tags}}
。
<p> </p><h4>在这里拖放</h4>
@drop
事件监听 addFile
方法,我们必须定义:
addFile(e) { let files = e.dataTransfer.files; [...files].forEach(file => { this.files.push(file); console.log(this.files) }); }
使用这种方法,放置在框中的所有文件都将记录在我们的控制台上。
但是,我们想在框内显示文件,因此我们必须将 <li>
元素修改为:
这样,每当我们将文件放入框中时,都会显示文件名和大小。
我们可以通过向 X
按钮添加点击事件来添加额外的功能,以从框中删除文件:@click = ‘removeFile(file)’
。
然后,我们定义 removeFile
方法:
removeFile(file) { this.files = this.files.filter(f => { return f != file; }); },
让我们定义压缩函数,该函数将压缩所选文件,这就是Axios的作用所在。我们将向我们在后端定义的 /compress
路由发出请求:
compressFile() { this.loading = true; let formdata = new FormData(); formdata.append('file', this.files[0]) axios.post('http://localhost:3000/compress', formdata, { responseType: 'blob' }).then(response => { let fileURL = window.URL.createObjectURL(new Blob([(response.data)])) let fileLink = document.createElement('a'); fileLink.href = fileURL; fileLink.setAttribute('download', `${this.files[0].name}.gz`); document.body.appendChild(fileLink); fileLink.click(); this.loading = false; }).catch(err => { this.loading = false; console.log(err) }) }
我们使用 FormData
上传文件。上载文件后,后端会压缩文件并将压缩后的文件返回给我们。
我们使用 URL.createObjectURL
创建一个 DOMstring
,其中包含表示给定对象的URL。然后,我们从后端下载给定的数据。
现在,我们需要在compress按钮中添加一个click事件,以侦听我们创建的方法:
<button> <span></span> 压缩 </button>
单击我们的压缩按钮将触发文件下载:
就是这样!
我们只是建立了一个简单的压缩应用程序。最后我们很想添加一个简单的方法,通过创建一个Vue.js过滤器,将我们的文件大小以千字节为单位进行格式化。
filters: { kb(val) { return Math.floor(val / 1024); } },
在模板中使用
{{ file.size | kb }} kb
这会将文件的大小格式化为更易读的格式。
Node.js使文件压缩变得容易。它可以进一步用于压缩HTTP请求和响应,以提高应用程序性能。要获得更多Zlib功能,可以查看Zlib上的Node.js文档。
源代码:https://github.com/dunizb/CodeTest/tree/master/Node/compressor
原文地址:https://blog.logrocket.com/build-a-file-compression-application-in-node-js-and-vue-js/
相关推荐:
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of Use Node.js+Vue.js to build file compression applications. For more information, please follow other related articles on the PHP Chinese website!