美文网首页
前端项目 如何实现将本地的静态图片资源上传到服务器

前端项目 如何实现将本地的静态图片资源上传到服务器

作者: 沉默紀哖呮肯伱酔 | 来源:发表于2023-08-02 18:21 被阅读0次

    目标:将前端项目的本地图片资源上传到服务器,并将静态文件的引用路径改为服务器的路径,不在读取本地文件路径。并删除本地图片资源。

    总共分三步

    1、第一步:首先把文件上传到静态服务器上,我们这里使用 node-ssh 创建sftp链接将文件上传

    关键代码如下

    ftpplugin.js 这是一个自定义的plugin

    const fs = require('fs')
    const fsPromises = require('fs').promises;
    const {NodeSSH} = require('node-ssh')
    const ssh = new NodeSSH()
    const path = require('path');
    
    class FtpPlugin {
      apply(compiler) {
        compiler.hooks.afterEmit.tapAsync('done', (compilation, callback) => {
          // 读取文件
          fs.readdir('dist', (err, files) => {
            if (err) {
              console.error(err);
            } else {
    
              files.map((itemDirName) => {
                console.log('itemDirName is', distPath + '/' + itemDirName)
                const currentDirPath = distPath + '/' + itemDirName
    
                if(fs.statSync(currentDirPath).isDirectory() && fs.existsSync(currentDirPath)){
                    // 调用上传图片的函数
                  uploadImg(itemDirName)
                }
              })
            }
          });
    
          callback();
        });
      }
    }
    
    /**
    * 删除文件
    */
    const deleteFile = (delPath, direct) => {
      delPath = direct ? delPath : path.join(__dirname, delPath)
      try {
        // 判断文件或文件夹是否存在
        if (fs.existsSync(delPath)) {
          fs.unlinkSync(delPath);
        } else {
          console.log('路径不存在', delPath);
        }
      } catch (error) {
        console.log('删除失败', error);
      }
    }
    
    /**
    * 删除文件夹
    */
    const deleteFolder = (delPath) => {
      delPath = path.join(__dirname, delPath)
    
      try {
        if (fs.existsSync(delPath)) {
          const delFileFunction = (currentPath) => {
            const files = fs.readdirSync(currentPath)
            for (let i = 0; i < files.length; i++) {
              const dirPath = path.join(currentPath, files[i])
              if (fs.statSync(dirPath).isDirectory()) {
                delFn(dirPath)
              } else {
                deleteFile(dirPath, true)
              }
            }
            // 只能删空文件夹
            fs.rmdirSync(address);
          }
          delFileFunction(delPath);
        } else {
          console.log('文件夹不存在', delPath);
        }
      } catch (error) {
        console.log('删除失败', error);
      }
    }
    
    const ftpConfig = {
      host: '', port: '', username: '', password: ''
    };
    
    const uploadImg = (itemDirName) => {
      return new Promise((resolve, reject) => { 
        // 创建一个链接
         ssh.connect(ftpConfig).then(() => {
    
          ssh.putDirectory(`local path`, `your server path`, {
            recursive: true,
            concurrency: 10,
          }).then(function(status) {
            console.log('the directory transfer was', status ? 'success' : '')
            // 调用删除文件夹函数
            deleteFolder(`local path`)
            ssh.dispose()
          })
    
        }).catch(err => {
          reject(err)
          console.log('ssh err', err)
          ssh.dispose()
        })
      })
    }
    
    

    2、第二步:使用这个Plugin

    // webpack config
    const ftpPlugin = require('./ftpPlugin');
    congif: {
        // ...
        plugins: [
    
            new ftpPlugin()
        ]   
        // ...
    }
    
    

    3、第三步:将loader处理后的资源路径加上前缀

    这一步很关键,取决于你的项目中的静态资源使用的是本地资源还是服务器资源

    // loader
            {
              test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
              loader: 'url-loader',
              exclude: [/node_modules/],
              options: {
                limit: 3 * 1024,
                name: `img/[name].[contentHash].[ext]`
                publicPath:  '静态服务器的域名'
              }
            },
    

    相关文章

      网友评论

          本文标题:前端项目 如何实现将本地的静态图片资源上传到服务器

          本文链接:https://www.haomeiwen.com/subject/ppyppdtx.html