electron-vue本地指定文件(不用input选择)转成文件流

250 阅读1分钟

在主进程中.

import { ipcMain } from 'electron'

const fs = require('fs')
const path = require('path')

fs.readFile(path.resolve(__dirname, 'C:\\DSS LightWeight\\DSS LightWeight Client\\Record\\1.jpg'), (err, data) => {
  if (err) throw err
  ipcMain.on('asynchronous-message', (event, arg) => {
    console.log(arg) // prints "ping"
    event.reply('asynchronous-reply', data)
  })

  ipcMain.on('synchronous-message', (event, arg) => {
    console.log(arg) // prints "ping"
    event.returnValue = 'pong'
  })
})

在渲染器进程 (网页) 中

  const { ipcRenderer } = require('electron')
      ipcRenderer.on('asynchronous-reply', (event, arg) => {
        console.log(arg) // prints "pong"
        let file = new File([arg], 'test.jpg', { type: 'image/jpg' })
        console.log(file)
      })
      ipcRenderer.send('asynchronous-message', 'ping')
1.选择指定目录的指定文件
2.转成文本流
3.form data的方式上传
nodejs文档
axios post request to send form data
     const fs = require('fs')
     const path = require('path')
     const fileNames = fs.readdirSync(path.resolve(__dirname, this.recordPath)) // 获取文件路径下的所有文件
     const currFileName = _.find(fileNames, item => item.includes(dayjs(1642042800000).format('YYYYMMDDHHmm'))) //获取指定文件名
     const filePath = path.resolve(__dirname, `${this.recordPath}${currFileName}`)
     let file
     //判断是否存在文件

     if (fs.statSync(filePath).isFile()) {
       fs.readFile(filePath, (err, data) => {
         if (err) throw err
         file = new File([data], currFileName, { type: 'video/mp4' })
         let bodyFormData = new FormData()
         bodyFormData.append('eventId', 'xxxxx')
         bodyFormData.append('devSn', 'xxxxxx')
         bodyFormData.append('type', 1)
         bodyFormData.append('file', file)
         this.$post(`/xxxxxxxx`, bodyFormData, { 'Content-Type': 'multipart/form-data' }).then(() => {
           this.$message({
             message: '上傳成功',
             type: 'success'
           })
         })
       })
     }