文件下载,文件复制,文件使用本地默认程序打开的API基础实现

This commit is contained in:
朱浩 2024-07-10 20:26:26 +08:00
parent dbcb17fc7e
commit 267bee6dd4
5 changed files with 122 additions and 6 deletions

View File

@ -20,6 +20,8 @@
"dependencies": {
"@electron-toolkit/preload": "^3.0.1",
"@electron-toolkit/utils": "^3.0.0",
"crypto-js": "^4.2.0",
"electron-dl-manager": "^3.0.0",
"electron-updater": "^6.1.7",
"element-plus": "^2.7.6",
"js-cookie": "^3.0.5",

97
src/main/file.js Normal file
View File

@ -0,0 +1,97 @@
const fs = require('fs')
const path = require('path')
import { ElectronDownloadManager } from 'electron-dl-manager';
const manager = new ElectronDownloadManager();
export default async function ({ app, shell, BrowserWindow, ipcMain }) {
const userDataPath = app.getPath('userData')
//默认浏览器打开url
ipcMain.on('open-url-browser', (e, url) => {
shell.openPath(url)
})
//使用默认应用打开本地文件
ipcMain.on('open-path-app', (e, path) => {
shell.openExternal(path)
})
//复制文件
ipcMain.on('copy-file-default', (e, { source, destination }) => {
copyFile(source, destination, (error, filePath) => {
e.reply('copy-file-default-reply', { error, filePath })
})
})
//下载文件
ipcMain.on('download-file-default', (e,url) => {
createFolder('selfFile').then(async ()=>{
const browserWindow = BrowserWindow.fromId(e.sender.id)
const id = await manager.download({
window: browserWindow,
url: url,
directory: userDataPath + '/selfFile/',
callbacks: {
onDownloadStarted: async ({ id, item, webContents }) => {
// Do something with the download id
},
onDownloadProgress: async ({ id, item, percentCompleted }) => {
browserWindow.webContents.invoke('download-progress', {
id,
percentCompleted,
// Get the number of bytes received so far
bytesReceived: item.getReceivedBytes(),
});
},
onDownloadCompleted: async ({ id, item }) => {
console.log(item)
},
onDownloadCancelled: async () => {},
onDownloadInterrupted: async () => {},
onError: (err, data) => {},
}
});
})
})
function copyFile(source, destination, callback) {
let path = userDataPath + '\\selfFile\\' + destination
createFolder('selfFile').then(() => {
const readStream = fs.createReadStream(source)
const writeStream = fs.createWriteStream(path)
readStream.on('error', (error) => {
callback(error, null)
})
writeStream.on('error', (error) => {
callback(error, null)
})
writeStream.on('close', () => {
callback(null, path)
})
readStream.pipe(writeStream)
})
}
function createFolder(folderName) {
return new Promise((resolve, reject) => {
const folderPath = path.join(userDataPath, folderName)
// 异步检查文件夹是否存在,不存在则创建
fs.access(folderPath, fs.constants.F_OK, (err) => {
if (err) {
fs.mkdir(folderPath, { recursive: true }, (mkdirErr) => {
if (mkdirErr) {
console.error(mkdirErr)
reject()
} else {
console.log(`Folder ${folderName} created successfully.`)
resolve()
}
})
} else {
console.log(`Folder ${folderName} already exists.`)
resolve()
}
})
})
}
}

View File

@ -2,7 +2,9 @@ import { app, shell, BrowserWindow, ipcMain } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import File from './file'
File({ app, shell, BrowserWindow, ipcMain })
function createWindow() {
// Create the browser window.
const mainWindow = new BrowserWindow({
@ -102,7 +104,6 @@ ipcMain.on('close-window', () => {
const win = BrowserWindow.getFocusedWindow();
win.close();
});
console.log(100)
ipcMain.on('set-winsize', (e, {x, y})=>{
const win = BrowserWindow.getFocusedWindow();
win.setSize(x,y);

View File

@ -4,8 +4,9 @@
:action="uploadUrl"
name="file"
:headers="headers"
:data="uploadData"
:data="uploadDatas"
:show-file-list="false"
:before-upload="beforeUpload"
class="editor-img-uploader"
>
<slot>
@ -15,6 +16,7 @@
</template>
<script>
import { getToken } from '@/utils/auth'
import CryptoJS from 'crypto-js';
export default {
name: 'Prepare',
props: {
@ -25,6 +27,7 @@ export default {
},
data() {
return {
uploadDatas: this.uploadData,
uploadUrl: import.meta.env.VITE_APP_BASE_API + '/smarttalk/file/upload',
headers: {
Authorization: 'Bearer ' + getToken()
@ -33,7 +36,20 @@ export default {
},
created() {},
mounted() {},
methods: {}
methods: {
beforeUpload(file) {
const fileReader = new FileReader();
console.log(file)
fileReader.onload = (e) => {
const buffer = e.target.result;
const md5 = CryptoJS.MD5(buffer).toString();
console.log('文件的MD5是:', md5);
this.uploadDatas.md5 = md5;
// 使md5
};
fileReader.readAsArrayBuffer(file);
}
}
}
</script>
<style scoped lang="scss"></style>

View File

@ -1 +1 @@
<template> <div> <FileUpload :multiple="true" :before-upload="handleBeforeUpload" :upload-data="uploadData" ></FileUpload> </div> </template> <script> import FileUpload from '@/components/file-upload/index.vue' export default { name: 'Prepare', components: { FileUpload }, data() { return { uploadData: { textbookId: '123', levelFirstId: '123', levelSecondId: '123', fileSource: '平台', fileFlag: '课件' } } }, :upload-data="uploadData" :upload-data="uploadData" :upload-data="uploadData" ></FileUpload> methods: { :upload-data="uploadData" </template> :upload-data="uploadData" <script> ) } } } </script> <style scoped lang="scss"></style>
<template> <div> <FileUpload :multiple="true" : :upload-data="uploadData" import FileUpload from '@/components/file-upload/index.vue' ></FileUpload> </div> </template> <script> import FileUpload from '@/components/file-upload/index.vue' const { ipcRenderer } = window.electron || {} export default { name: 'Prepare', components: { FileUpload }, data() { return { fileUrl: "https://wzyzoss.eos-chongqing-3.cmecloud.cn/2024/7/10/117cdf208c6b4e58bf2b73369eaf3cb5.pptx", filePath: "C:/Users/zhuhao/Desktop/工作文档/0901高一【数学(人教A版)】集合的概念-PPT课件.pptx", uploadData: { textbookId: '123', levelFirstId: '123', levelSecondId: '123', fileSource: '平台', fileFlag: '课件' } } }, created() { ></FileUpload> :upload-data="uploadData" ipcRenderer.on('copy-file-default-reply', (e,param)=>{ this.callback(param) }) :upload-data="uploadData" before-upload="handleBeforeUpload" mounted() { // const destination = '0901高一【数学(人教A版)】集合的概念-PPT课件.pptx' setTimeout(()=>{ // ipcRenderer.send('open-path-app',this.filePath) // const source = 'D:\\edufile\\0901高一【数学(人教A版)】集合的概念-PPT课件.pptx' // ipcRenderer.send('copy-file-default',{ source, destination }) </div> :upload-data="uploadData" </div> ></FileUpload> }, methods: { callback({error, filePath}) { </div> </template> </div> <script> return } console.log('File copied to:', filePath) } } } </script> <style scoped lang="scss"></style>