nodejs + fastDFS 文件上传下载 服务器转发实现

koa + koa-body上传文件需先设置参数:multipart=true

import koaBody from 'koa-body'

app.use(koaBody({multipart:true}))

利用可读流获取文件数据

let Writable = require('stream').Writable

class writableStream extends Writable{

    constructor(){

        super()

        this.binaryArr = []

        this.binarySize = 0

    }

    _write(chunk, enc,done){

        this.binaryArr.push(chunk)

        this.binarySize += chunk.length

        done()

    }

    getBinary(){

        return {

            binaryArr: this.binaryArr,

            binarySize: this.binarySize

        }

    }

}

fastdfs-client 下载 npm install fastdfs-client

import dfsClient from 'fastdfs-client'

 

 

class fastDFS {

    constructor(){

        if(fastdfs_client == null){

            fastdfs_client = new dfsClient({

                trackers: [

                    {

                        host: 'ip',//tracker 服务器ip

                        port: 22122 //tracker 端口

                    }

                ],

                // 默认超时时间10s

                timeout: 10000,

                // 默认后缀

                // 当获取不到文件后缀时使用

                defaultExt: 'txt',

                // charset默认utf8

                charset: 'utf8'

            })

        }

    }

//文件上传

    upload(file){

         // file FormData提交数据

        let type = file.fields.type //文件类型

        let name = file.fields.name //文件名称

        let size = file.fields.size //文件大小

        let files = file.files //文件

        fastdfs_client.upload(files.file.path,{

            method: 'upload',

            group: 'group1', 

            size: size,

            ext: type

        }).then((fileId) => {

            console.log('返回fileId为:',fileId)

        }).catch(err => {

            console.log('上传异常:',err)

        })

    }

//删除文件

    delete(fileId){

        fastdfs_client.del(fileId).then(() => {

            console.log('删除成功',fileId)

        }).catch(err => {

            console.log('删除异常:',err)

        })

    }

//获取文件信息

    getFileInfo(fileId){

        fastdfs_client.getFileInfo(fileId).then( function(fileInfo){

            console.log(fileInfo)

        }).catch(err => {

            console.log('查询异常:',err)

        })

    }

//下载文件

    async download(fileId){

        return await new Promise((resolve,reject) => {

            let ws = new writableStream()

            fastdfs_client.download(fileId, ws).then(() => {

                 //文件下载完成

                let value = ws.getBinary() //获取文件数据

                let buffer = Buffer.alloc(value.binarySize) 

                let index = 0

                for(let i in value.binaryArr){

                    value.binaryArr[i].copy(buffer,index)

                    index += value.binaryArr[i].length

                }

                resolve(buffer) //返回文件数据

            }).catch(err => {

                console.log('下载异常',err)

                resolve(err)

            })

        })

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
由于涉及到服务器文件的遍历,需要使用服务器端的代码。以下是使用Node.js实现服务器文件遍历的示例代码: ```javascript const fs = require('fs'); // 定义遍历函数 function traverseFolder(folderPath) { fs.readdir(folderPath, function(err, files) { if (err) { console.error(err); return; } files.forEach(function(file) { const fullPath = folderPath + '/' + file; fs.stat(fullPath, function(err, stats) { if (err) { console.error(err); return; } if (stats.isDirectory()) { // 如果是文件夹,递归进入 traverseFolder(fullPath); } else { // 如果是文件,可以做相应的处理 console.log(fullPath); } }); }); }); } // 调用遍历函数 traverseFolder('/path/to/your/folder'); ``` 上述代码中,`traverseFolder`函数用于遍历指定路径下的所有文件和文件夹。对于每个文件夹,递归进入;对于每个文件,可以做相应的处理,例如打印路径。 此外,还需要在Node.js中使用HTTP模块搭建一个简单的Web服务器,以便在浏览器中访问文件列表。以下是示例代码: ```javascript const http = require('http'); const fs = require('fs'); const path = require('path'); // 定义遍历函数 function traverseFolder(folderPath, callback) { fs.readdir(folderPath, function(err, files) { if (err) { callback(err); return; } const results = []; files.forEach(function(file) { const fullPath = folderPath + '/' + file; fs.stat(fullPath, function(err, stats) { if (err) { callback(err); return; } const item = { name: file, path: fullPath, isDirectory: stats.isDirectory() }; if (stats.isDirectory()) { // 如果是文件夹,递归进入 traverseFolder(fullPath, function(err, children) { if (err) { callback(err); return; } item.children = children; results.push(item); if (results.length === files.length) { callback(null, results); } }); } else { // 如果是文件,直接添加到结果数组中 results.push(item); if (results.length === files.length) { callback(null, results); } } }); }); }); } // 创建HTTP服务器 const server = http.createServer(function(req, res) { // 获取当前路径 const currentPath = '.' + req.url; // 如果是文件,直接返回文件内容 if (fs.existsSync(currentPath) && fs.statSync(currentPath).isFile()) { fs.readFile(currentPath, function(err, data) { if (err) { res.writeHead(500); res.end(); return; } res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end(data); }); return; } // 如果是文件夹,返回文件列表 traverseFolder(currentPath, function(err, results) { if (err) { res.writeHead(500); res.end(); return; } // 生成HTML代码,展示文件列表 let html = '<ul>'; results.forEach(function(item) { html += '<li>'; if (item.isDirectory) { html += '<a href="' + item.path + '">' + item.name + '</a>'; if (item.children) { html += '<ul>'; item.children.forEach(function(child) { html += '<li><a href="' + child.path + '">' + child.name + '</a></li>'; }); html += '</ul>'; } } else { html += item.name; } html += '</li>'; }); html += '</ul>'; res.writeHead(200, { 'Content-Type': 'text/html' }); res.end(html); }); }); // 启动服务器 server.listen(8080, function() { console.log('Server is listening on port 8080'); }); ``` 上述代码中,`traverseFolder`函数的作用与之前的示例代码相同,但这里将结果包装为一个对象数组,以便在浏览器中进行展示。同时,返回的结果是一个异步回调函数的参数,而非直接输出到控制台。 在HTTP服务器中,首先判断当前请求的路径是否是一个文件,如果是,则直接返回文件内容。否则,调用`traverseFolder`函数获取文件列表,并生成HTML代码,向浏览器输出。需要注意的是,这里使用了`fs.existsSync`和`fs.statSync`函数判断当前路径是否是一个文件,以避免遍历整个文件夹。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值