我在这里有以下代码行,在点击发送按钮时显示用户文本(模拟正在发送的聊天消息)
<script>
$('#subbut').click(function(){
var user_msg = $("#user_msg").val();
$("#msg").append('<p>User says:'+user_msg+'</p>');
</script>
<body>
<div id="msg"></div>
<input type="text" name="user_msg" id="user_msg">
<input type="submit" value="Submit" id="subbut">
</body>
但是我也想这样做以输入图像。
<body>
<div id="msg"></div>
<input type="file" name="newImage" id="upload-photo">
<input type="submit" value="Submit" id="subbut">
</body>
当单击#subbut按钮时,如何访问图像并将其附加(显示图像)到#msg div?我在这里看过类似的东西Preview an image before it is uploaded,但我似乎无法适应它。
答案 0 :(得分:1)
<div id="image-wrapper"></div>
<input id="upload-image" type="file" accept=".jpg"/>
<input id="subbut" type="submit" value="Submit"/>
<script>
var _URL = window.URL || window.webkitURL;
$("#subbut").click(function () {
var file;
var image;
if ((file = $("#upload-image")[0].files[0])) {
image = new Image();
image.onload = function () {
$("#image-wrapper").append(this);
$(this).attr("id", "image");
}
image.src = _URL.createObjectURL(file);
}
});
</script>
答案 1 :(得分:0)
<input type="file" id="inputFileToLoad" onchange="chnageimgupdate()" />
function loadImageFileAsURL()
{
var filesSelected = document.getElementById("inputFileToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var imageLoaded = document.createElement("img");
imageLoaded.src = fileLoadedEvent.target.result;
document.body.appendChild(imageLoaded);
};
fileReader.readAsDataURL(fileToLoad);
}
}
}