我在Bootstrap模式下上传图像,然后裁剪该图像,因此必须预览上传的图像以选择要裁剪的区域。
现在我正在使用createObjectURL
,如https://caniuse.com/#search=createObjectURL所示,看来它不支持旧的浏览器。
代码如下:
$("#input").on("change", function(e) {
var _URL = window.URL || window.webkitURL,
file = this.files[0],
image = new Image();
image.onload = function(e) {
//Check image dimensions.
if( this.width > 1000 || this.height > 1000 ){
alert( 'Please select smaller image.' );
}else{
//Change the source of the image on modal to the selected image.
$('#image').attr('src', _URL.createObjectURL(file));
//Open the bootstrap modal.
$('#modal').modal('show');
}
}
//Save space
window.URL.revokeObjectURL(image.src);
//Clear selected file
$(e.target.id).val('');
});
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>
<!-- Input to upload images -->
<input type="file" id="input" name="image">
<!-- Modal to show uploaded image on -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="modalLabel">Image Upload</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div> <!-- .modal-header -->
<div class="modal-body">
<div class="container">
<!-- Uploaded Image -->
<img id="image" src="" alt="Picture">
</div> <!-- .container -->
</div> <!-- .modal-body -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div> <!-- .modal-footer -->
</div> <!-- .modal-content -->
</div> <!-- .modal-dialog -->
</div> <!-- .modal -->
是否有更好的兼容方式?
或者检查每个浏览器,然后使用该浏览器支持的特定代码?
这些旧的浏览器不可以显示上传的图像吗?我的意思是在createObjectURL
之前,您将如何显示上传的图像?
我预览了一些相关问题,包括this question,但找不到解决方案。