1. 实现原理
通过双层结构实现
<div>
上传:<input type="text">
<img src="" alt="">
</div>
2. html
<style>
.file-view {
height: 80px;
width: 80px;
padding: 2px;
border: 1px dotted #dddddd;
position: relative;
}
.file-view .view-file {
position: absolute;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1001
}
.file-view .view-img {
height: 100%;
width: 100%;
border: 0;
overflow: hidden;
}
</style>
<div class="file-view">
<input class="view-file" type="file" name="img">
<img class="view-img" src="{% static 'web/images/default-image.png'
%}">
</div>
3. js
$(function () {
bindChangeImageFile();
});
function bindChangeImageFile() {
$('#areaImage').on('change', '.view-file', function () {
var fileObject = $(this)[0].files[0];
var blob = window.URL.createObjectURL(fileObject);
$(this).next().attr('src', blob);
$(this).next().load(function () {
window.URL.revokeObjectURL(blob);
})
})
4. 详解
https://www.cnblogs.com/wupeiqi/articles/9322297.html