电子:获取上传文件的完整路径
Electron: get full path of uploaded file
我现在正在使用 Electron 构建 GUI。 (例如用于桌面应用程序的 PhoneGap)
有没有办法为 <input type="file">
中签入的文件启用完整路径?
现在已安装 C:\fakepath\dataset.zip
。 (目录名不是 "fakepath",而是 document.getElementById("myFile").value
的值)
或者,还有其他方法可以 select 一个文件吗?
根据此回答 How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?。
出于安全原因,无法执行您正在尝试的操作
但是,您可以像我在我从事的电子项目中所做的那样解决问题。
- 创建一个 HTML 按钮
然后在渲染器进程中为您之前创建的按钮创建一个事件侦听器。
const ipc = require('electron').ipcRenderer;
const buttonCreated = document.getElementById('button-created-id');
buttonCreated.addEventListener('click', function (event) {
ipc.send('open-file-dialog-for-file')
});
然后在主进程中使用showOpenDialog
选择一个文件然后将full path
发送回渲染器过程。
ipc.on('open-file-dialog-for-file', function (event) {
if(os.platform() === 'linux' || os.platform() === 'win32'){
dialog.showOpenDialog({
properties: ['openFile']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
} else {
dialog.showOpenDialog({
properties: ['openFile', 'openDirectory']
}, function (files) {
if (files) event.sender.send('selected-file', files[0]);
});
}});
然后在 渲染器进程 你得到 full path
.
ipc.on('selected-file', function (event, path) {
console.log('Full path: ', path);
});
因此您可以获得与输入类型文件类似的行为并获得完整路径。
<script>const electron = require('electron');</script>
<button id="myFile" onclick="this.value=electron.remote.dialog.showOpenDialog()[0]">UpdateFile</button>
现在,document.getElementById("myFile").value
将包含所选文件的完整路径。
Electron 添加了一个 path
property to File 对象,因此您可以使用以下方式从输入元素获取真实路径:
document.getElementById("myFile").files[0].path
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
const ko = require('knockout')
const fs = require('fs');
const request = require('request-promise');
// replace with your own paths
var zipFilePath = 'C:/Users/malco/AppData/Roaming/Wimpsdata/Wimpsdata.zip';
var uploadUri = 'http://localhost:59887/api/Collector/Upload'
var request = require('request');
request.post({
headers: { 'content-type': 'application/zip' },
url: uploadUri,
body: fs.createReadStream(zipFilePath)
}, function (error, response, body) {
console.log(body);
location.href = 'ScanResults.html';
});
</script>
ASP .NET WebAPI 控制器
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Wimps.Services.Business;
namespace Wimps.Services.Controllers
{
public class CollectorController : ApiController
{
public async Task<bool> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Byte[] byteArray = await content.ReadAsByteArrayAsync();
string newFileName = Guid.NewGuid().ToString();
string newFilePath = fileuploadPath + "\" + newFileName + ".zip";
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.WriteAllBytes(newFilePath, byteArray);
string unzipTo = fileuploadPath + "\" + newFileName;
Directory.CreateDirectory(unzipTo);
DirectoryInfo di = new DirectoryInfo(unzipTo);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
ZipFile.ExtractToDirectory(newFilePath, unzipTo);
return true;
}
catch (Exception e)
{
// handle exception here
return false;
}
}
}
}
需要将密钥添加到 web 配置文件上传
<configuration>
<appSettings>
... other keys here
<add key="FileUploadLocation" value="C:\Temp\Uploads" />
</appSettings>
其余应用配置
...
...
已接受的答案对原始问题非常有用,但@Piero-Divasto 的答案对我来说效果更好。
我需要的是 目录 的路径名,它可能相当大。使用接受的答案,这可以在处理目录内容时阻止主进程几秒钟。使用 dialog.showOpenDialog(...)
可以获得近乎即时的响应。唯一的区别是 dialog.showOpenDialog
不再接受回调函数,取而代之的是 returns 承诺:
ipcMain.on("open-file-dialog-for-dir", async event => {
const dir = await dialog.showOpenDialog({ properties: ["openDirectory"] });
if (dir) {
event.sender.send("selected-dir", dir.filePaths[0]);
}
});
我现在正在使用 Electron 构建 GUI。 (例如用于桌面应用程序的 PhoneGap)
有没有办法为 <input type="file">
中签入的文件启用完整路径?
现在已安装 C:\fakepath\dataset.zip
。 (目录名不是 "fakepath",而是 document.getElementById("myFile").value
的值)
或者,还有其他方法可以 select 一个文件吗?
根据此回答 How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?。
出于安全原因,无法执行您正在尝试的操作但是,您可以像我在我从事的电子项目中所做的那样解决问题。
- 创建一个 HTML 按钮
然后在渲染器进程中为您之前创建的按钮创建一个事件侦听器。
const ipc = require('electron').ipcRenderer; const buttonCreated = document.getElementById('button-created-id'); buttonCreated.addEventListener('click', function (event) { ipc.send('open-file-dialog-for-file') });
然后在主进程中使用
showOpenDialog
选择一个文件然后将full path
发送回渲染器过程。ipc.on('open-file-dialog-for-file', function (event) { if(os.platform() === 'linux' || os.platform() === 'win32'){ dialog.showOpenDialog({ properties: ['openFile'] }, function (files) { if (files) event.sender.send('selected-file', files[0]); }); } else { dialog.showOpenDialog({ properties: ['openFile', 'openDirectory'] }, function (files) { if (files) event.sender.send('selected-file', files[0]); }); }});
然后在 渲染器进程 你得到
full path
.ipc.on('selected-file', function (event, path) { console.log('Full path: ', path); });
因此您可以获得与输入类型文件类似的行为并获得完整路径。
<script>const electron = require('electron');</script>
<button id="myFile" onclick="this.value=electron.remote.dialog.showOpenDialog()[0]">UpdateFile</button>
现在,document.getElementById("myFile").value
将包含所选文件的完整路径。
Electron 添加了一个 path
property to File 对象,因此您可以使用以下方式从输入元素获取真实路径:
document.getElementById("myFile").files[0].path
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
const ko = require('knockout')
const fs = require('fs');
const request = require('request-promise');
// replace with your own paths
var zipFilePath = 'C:/Users/malco/AppData/Roaming/Wimpsdata/Wimpsdata.zip';
var uploadUri = 'http://localhost:59887/api/Collector/Upload'
var request = require('request');
request.post({
headers: { 'content-type': 'application/zip' },
url: uploadUri,
body: fs.createReadStream(zipFilePath)
}, function (error, response, body) {
console.log(body);
location.href = 'ScanResults.html';
});
</script>
ASP .NET WebAPI 控制器
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using Wimps.Services.Business;
namespace Wimps.Services.Controllers
{
public class CollectorController : ApiController
{
public async Task<bool> Upload()
{
try
{
var fileuploadPath = ConfigurationManager.AppSettings["FileUploadLocation"];
var provider = new MultipartFormDataStreamProvider(fileuploadPath);
var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
foreach (var header in Request.Content.Headers)
{
content.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
Byte[] byteArray = await content.ReadAsByteArrayAsync();
string newFileName = Guid.NewGuid().ToString();
string newFilePath = fileuploadPath + "\" + newFileName + ".zip";
if (File.Exists(newFilePath))
{
File.Delete(newFilePath);
}
File.WriteAllBytes(newFilePath, byteArray);
string unzipTo = fileuploadPath + "\" + newFileName;
Directory.CreateDirectory(unzipTo);
DirectoryInfo di = new DirectoryInfo(unzipTo);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
ZipFile.ExtractToDirectory(newFilePath, unzipTo);
return true;
}
catch (Exception e)
{
// handle exception here
return false;
}
}
}
}
需要将密钥添加到 web 配置文件上传
<configuration>
<appSettings>
... other keys here
<add key="FileUploadLocation" value="C:\Temp\Uploads" />
</appSettings>
其余应用配置 ... ...
已接受的答案对原始问题非常有用,但@Piero-Divasto 的答案对我来说效果更好。
我需要的是 目录 的路径名,它可能相当大。使用接受的答案,这可以在处理目录内容时阻止主进程几秒钟。使用 dialog.showOpenDialog(...)
可以获得近乎即时的响应。唯一的区别是 dialog.showOpenDialog
不再接受回调函数,取而代之的是 returns 承诺:
ipcMain.on("open-file-dialog-for-dir", async event => {
const dir = await dialog.showOpenDialog({ properties: ["openDirectory"] });
if (dir) {
event.sender.send("selected-dir", dir.filePaths[0]);
}
});