文件中选择用户时如何获取文件的路径目录"/>
[在输入类型文件中选择用户时如何获取文件的路径目录
我想在输入类型文件中选择文件时获取文件在计算机中的位置。这是ejs文件中的代码。
<html>
<form name="insertData" method="POST" action="/" enctype="multipart/form-data">
<input class="inputInsert" type="file" accept=".xlsx" name='filename'>
<button class="insertButton">UPLOAD</button>
</form>
</html>
例如:我在计算机中选择文件test.xlsx,我想将该文件的路径(C:/Users/HP/Desktop/test.xlsx)发送到控制器。这是我在控制器中的代码。
exports.insertData = function(req,res) {
var pathFile = //location of file that user selected
res.render('home', {'path': pathFile})
}
我需要更改位置文件,因为用户在他们的计算机中选择了文件。谢谢您的帮助。
回答如下:我们无法在服务器端获取任何本地目录的路径。因此,它只能在客户端获取。HTML代码:
<html>
<body>
<form method="POST" action="/" enctype="multipart/form-data">
<input class="inputInsert" type="file" accept=".xlsx" name="filename" id="fileUpload"/>
<button class="insertButton">UPLOAD</button>
</form>
<script>
$('#fileUpload').change(function (e) {
console.log($(this).val()) // This will print out the file path
console.log(e.target.files[0])
/*
The above line will print some more details about the file
[object File]{
arrayBuffer: function arrayBuffer() { [native code] },
lastModified: 1589551849373,
lastModifiedDate: [object Date] {
$constructor: function Date() { [native code] },
$family: function(){return i}
},
name: "LoremIpsum.xlsx",
size: 1205,
slice: function slice() { [native code] },
stream: function stream() { [native code] },
text: function text() { [native code] },
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
webkitRelativePath: ""
}
*/
})
</script>
</body>
</html>
如果您打算在服务器端上传文件,我认为您应该看看express-fileupload
Express.js代码:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
// Default options applied currently. For more configuration go to express-fileupload link above
app.use(fileUpload());
exports.insertData = function(req,res) {
// Ignore If you don't want to check if files were uploaded or not.
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send('No files were uploaded.');
}
// The name of the input field (i.e. "filename") is used to retrieve the uploaded file
let pathFile= req.files.filename;
res.render("home", {"path": pathFile})
});
});
Object.keys()方法用于返回一个数组,该数组的元素是与直接在对象上发现的可枚举属性相对应的字符串。
Multer也适合使用express.js上传文件注意:提到的模块适用于express.js
更多推荐
[在输入类型文件中选择用户时如何获取文件的路径目录
发布评论