Node.js 上传文件

 

因为文件上传是通过给定的WebService来上传的,所以需要再Node.js 里面使用soap模块请求webService, 并且需要注意的是在Node.js 使用soap, 要求webservice的参数接收均使用字符串格式来接收, 或许可能不是,但是我之前用model来接收参数,一直失败,后面将所有接收参数改为String就成功了。

const soap = require("soap");
const fs = require("fs");
const multer = require('multer');

const Upload = multer({ dest: 'uploads/'});

const GetCurrentDateTime = function() {
    let now = new Date();
    let year = now.getFullYear();     //得到年份
    let month = (now.getMonth() + 1) < 10 ? `0${now.getMonth() + 1}` : (now.getMonth() + 1);    //得到月份
    let date = now.getDate() < 10 ? `0${now.getDate()}`: now.getDate();        //得到日期
    let hour = now.getHours() < 10 ? `0${now.getHours()}` : now.getHours();        //得到小时
    let minu = now.getMinutes() < 10 ? `0${now.getMinutes()}` : now.getMinutes();    //得到分钟
    let sec = now.getSeconds() < 10 ? `0${now.getSeconds()}` : now.getSeconds();        //得到秒

    return `${year}-${month}-${date}T${hour}:${minu}:${sec}`;
}

export {
    GetCurrentDateTime,
    Upload,
    soap,
    fs
};

 

import Express from 'express';

import {
    GetCurrentDateTime, Upload, fs, soap
} from '../interface/xxxxx'; // 上面的文件

let router = Express.Router();
router.use(Upload.single('file')); // 单一模式
let config = Config(__dirname)

// 上传文件
router.post('/upload',
    (req, res, next) => {
        let file = req.file;
        let url = config.UploadService; // 从config下根据环境来取上传的service
        let changePathName = 'uploads\\'+ file.originalname;
        // console.log('changePathName: '+changePathName);
        // 将文件名重命名为原始文件名,而不是随机字符串
        fs.renameSync(file.path, changePathName);
        // 同步读取文件流
        let buffer = new Buffer.from(fs.readFileSync(changePathName, {encoding:'binary'}), 'binary');
        
        soap.createClient(url, function(err, client) {
        var args = {
                argFileStream: buffer.toString('base64'),
          strFileName: file.originalname,
          strFilePath: changePathName,
           strFileDesc: req.body.Remark,
          Create_By: req.body.User,
          Create_Dt: GetCurrentDateTime()
          //Create_Dt: '2020-09-02T11:09:00'
     }           
     client.UploadFile(args, function(err, result) {
          if(err) {
                    console.log('err:'+ JSON.stringify(err));
                    res.status(200).json(responseFormat(false, null, '文件上传失败.', err));
                } else {
                    console.log('result:'+JSON.stringify(result));

                    // 1. 因为上传成功会返回文件的下载URL, 可以检查Result里面是否存在字符http来确定是否上传成功
                    if(result.message.indexOf("http") == -1){
                        res.status(200).json(responseFormat(false, result, '文件上传文件失败.', err));
                    } else {
                        // 2. 向数据库写入数据, 并返回信息
                        res.status(200).json(responseFormat(true, {URL: result.message}, '文件上传成功并且下载地址关联信息写入成功.'));
                    }
                }
                // 因为使用了multer,会临时保存文件在\uploads\文件夹下,无论上传是否成功最后都删除临时文件,释放存储空间
                fs.unlink(changePathName, err => {
                    if(err) {
                        console.log(err);
                        return false;
                    }
                });
            });
        });
    }
);

module.exports = router;

 

posted @ 2021-12-24 16:34  一口一个小馒头  阅读(612)  评论(0编辑  收藏  举报