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 itcompressor
, and set up a new Node by runningnpm init -y
. js project.
We write the back-end service first, so create anotherserver
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 ##serverdirectory:
npm i --save koa koa-router nodemon multer cors
index.jsfile in the
serverdirectory. This is what we will Where the backend code is written.
.gitignorefile and add
node_modulesto it, this will prevent the
node_modulesfolder 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'); });
corsas 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.
gzipmethod.
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); } });
/compressroute, which is a
POSTrequest, and then pass the Multer middleware in that route. Our
Multermiddleware will return the file buffer, which is stored in the
fileBuffervariable.
compresseddirectory and save the compressed files in it.
compresseddirectory.
const destination = `compressed/${req.file.originalname}.gz`;
gzipto compress the file, which takes
fileBufferas the first parameter and then a callback function as the second parameter. The callback function consists of any possible errors and compressed responses.
compresseddirectory, the file will have the
.gzfile extension because it is used Identifies Zlib compression.
package.lock.jsonfile, its size is 48kb.
clientdirectory inside the
compressorroot directory. In the
clientdirectory, create two files:
index.htmland
main.js.
main.jsfile at the end of the body tag.
nbsp;html>Vue Compressor
压缩
对于此应用程序,用户将通过拖放添加其文件。让我们为我们的应用程序定义一个简单的用户界面。
修改模板为:
nbsp;html>Vue Compressor
在这里拖放
你可以使用任何实时服务器运行你的应用程序,这里我使用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}}
。
在这里拖放
@drop
事件监听addFile
方法,我们必须定义:
addFile(e) { let files = e.dataTransfer.files; [...files].forEach(file => { this.files.push(file); console.log(this.files) }); }
使用这种方法,放置在框中的所有文件都将记录在我们的控制台上。
但是,我们想在框内显示文件,因此我们必须将元素修改为:
这样,每当我们将文件放入框中时,都会显示文件名和大小。
我们可以通过向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事件,以侦听我们创建的方法:
单击我们的压缩按钮将触发文件下载:
就是这样!
我们只是建立了一个简单的压缩应用程序。最后我们很想添加一个简单的方法,通过创建一个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!