JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<input type="text" ID="txtPhoto" readonly="readonly" class="input" style="width:400px" />
<br/>
<div class="file-Upload button-pick" style="width:160px;margin-left:240px;">
<span>選擇照片</span>
<input type="file" ID="file" runat="server" class="upload input" />
</div>
<img id="img0" style="z-index:1;" >
CSS
.button-pick {
font-family: \5FAE\8EDF\6B63\9ED1\9AD4,\65B0\7D30\660E\9AD4, Microsoft Jhenghei;
margin-top:5px;
cursor: pointer;
/*width: 160px;*/
height:40px;
font-weight: bold;
background-color: #E88EB0;
vertical-align: center;
color: #ffffff;
font-size: 18px;
font-size: 1rem;
line-height: 40px;
text-align: center;
border: none;
border-radius: 0;
outline: none;
}
.button-pick:hover, .button-Send:hover, .button-Uploed:hover
{
background-color: #A02050;
}
.file-Upload {
position: relative;
overflow: hidden;
}
.file-Upload input.upload {
position: absolute;
top: 0;
right: 0;
margin: 0;
padding: 0;
font-size: 20px;
cursor: pointer;
opacity: 0;
filter: alpha(opacity=0);
}
JavaScript
$(document).ready(function () {
$("#file").change(function () {
var objUrl = getObjectURL(this.files[0]);
//console.log("objUrl = " + objUrl);
if (objUrl) {
$("#img0").attr("src", objUrl);
//圖片等比縮放
img = new Image();
img.src = objUrl;
img.onload = function() {
var picWidth = this.width;
var picHeight = this.height;
var pre = 1;
console.log("Width:" + picWidth);
console.log("Height:" + picHeight);
if (picWidth > picHeight) {
pre = 600 / picWidth;
} else if (picHeight > picWidth) {
pre = 600 / picHeight;
}
img.width = picWidth * pre;
img.height = picHeight * pre;
$("#img0").attr("style", "width:" + img.width + "px;").attr("style", "height:" +img.height + "px;");
}
$("#txtPhoto").val(this.value);
}
});
});
/**
* 建立一個可存取到該file的url
* PS: 瀏覽器必須支援HTML5 File API
*/
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) { // basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) { // mozilla(firefox)
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) { // webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
console.log(url)
return url;
//console.log(url)
}