在JavaScript中,出于安全考虑,直接获取<input type="file">
控件的本地文件路径是不可能的。这是由于浏览器的同源策略和隐私限制,防止恶意脚本获取用户的敏感信息。
虽然不能获取文件的本地路径,但可以通过File API读取文件内容并进行处理。以下是一个示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File API Example</title>
</head>
<body>
<input type="file" id="fileInput">
<img id="preview" src="" alt="File Preview" style="max-width: 300px; margin-top: 20px;">
<script>
document.getElementById('fileInput').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.getElementById('preview');
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
</script>
</body>
</html>
<img>
标签。change
事件。FileReader
对象读取文件内容,并在读取完成后将图片预览显示在<img>
标签中。通过这种方式,可以在不获取文件本地路径的情况下,对用户选择的文件进行处理和预览。
领取专属 10元无门槛券
手把手带您无忧上云