如何使用jQuery客户端上传图像并将其添加到div?

所以基本上,正如标题所说,我想要一个允许客户上传图像的上传按钮,然后它将显示在div中。

当然,这只是客户端,所以如果页面被刷新,那么图像就会消失。

然后,图像将相应地设置样式并给定固定的宽度和高度。

我在网上搜索,根本找不到任何东西。

jQuery很新,虽然我可以在Javascript中流利地编码。

如果没有AJAX和/或PHP的帮助,也不确定这是否可行。 如果可能的话,想避免这些。

非常感谢所有帮助。

这是一个有用的JSFiddle , 可以满足您的需求

function readURL(e) { if (this.files && this.files[0]) { var reader = new FileReader(); $(reader).load(function(e) { $('https://stackoverflow.com/questions/19005678/how-to-upload-an-image-with-jquery-client-side-and-add-it-to-a-div/#blah').attr('src', e.target.result); }); reader.readAsDataURL(this.files[0]); } } $("https://stackoverflow.com/questions/19005678/how-to-upload-an-image-with-jquery-client-side-and-add-it-to-a-div/#imgInp").change(readURL); 

作为旁注,上面的解决方案使用jQuery,虽然它不是工作解决方案所必需的,仅限Javascript:

 function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { document.getElementById('blah').src = e.target.result; } reader.readAsDataURL(input.files[0]); } } And the HTML:  your image 

请参阅此处制作的jsFiddle Fork ,以帮助解释如何更多地使用jQuery来回答您的一些评论问题。

请参阅http://www.codeforest.net/html5-image-upload-resize-and-crop

你可以使用像canvas这样的HTML5标签……你也可以使用像jCrop这样的Jquery插件。