如何在 JavaScript 中预览上传前的图片?
javascriptweb developmentobject oriented programming更新于 2025/8/17 9:48:17
要上传图片,请在 JavaScript 中使用 FileReader()。以下是 JavaScript 代码 −
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form runat="server">
<input type='file' id="yourImage" />
<img id="chooseImage" src="#" alt="image" />
</form>
<script>
function readImage(fileInput) {
if (fileInput.files && fileInput.files[0]) {
var takingInputFile = new FileReader();
takingInputFile.onload = function(event) {
$('#chooseImage').attr('src', event.target.result);
}
takingInputFile.readAsDataURL(fileInput.files[0]);
}
}
$("#yourImage").change(function() {
readImage(this);
});
</script>
</body>
</html>
要运行上述程序,请保存文件名为anyName.html(index.html),然后右键单击该文件并选择选项在 VS 中使用实时服务器打开代码编辑器。
输出

相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

