jquery上传图片预览
① 如何添加、删除HTML结点 & 上传图片预览
用到Jquery插件
<div class="aa"></div>
<div class="bb"></div>
添加节点: $(".aa").append(".bb"); 节点aa后面添加bb节点
删除节点: $(".bb").remove(); 删除最后一个节点$(".bb:last").remove();
上传图片预览:
$("#flie").change(function(){ //上传 控件 上传的 预览
$("#img1").attr("src","file:///"+$("#flie").val());
})
<input id="flie" name="flie" type="file" /><br>
<img id="img1" width="500" height="200" src="">
② jqueryajax不能上传图片
不能上传的原因可能是jquery插件使用不正确。
解决方法:
1、在head之间加入jquery引用
<scripttype="text/javascript" src="jquery.js"></script>
<scriptsrc="project/js/jquery.form.js" type="text/javascript"></script>
<scriptsrc="project/js/fileload.js" type="text/javascript"></script>
2、定义fileload.js,代码如下:
function createHtml(obj) {
var htmstr = [];
htmstr.push( "<form id='_fileForm' enctype='multipart/form-data'>");
htmstr.push( "<table cellspacing="0" cellpadding="3" style="margin:0 auto; margin-top:20px;">");
htmstr.push( "<tr>");
htmstr.push( "<td class="tdt tdl">请选择文件:</td>");
htmstr.push( "<td class="tdt tdl"><input id="loadcontrol" type="file" name="filepath" id="filepath" /></td>");
htmstr.push( "<td class="tdt tdl tdr"><input type="button" onclick="fileloadon()" value="上传"/></td>");
htmstr.push( "</tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" colspan='3'style='text-align:center;'><div id="msg"> </div></td> </tr>");
htmstr.push( "<tr> <td class="tdt tdl tdr" style=" vertical-align:middle;">图片预览:</td> <td class="tdt tdl tdr" colspan="2"><div style="text-align:center;"><img src="project/Images/NoPhoto.jpg"/></div></td> </tr>");
htmstr.push( "</table>")
htmstr.push( "</form>");
obj.html(htmstr.join(""));
}
function fileloadon() {
$("#msg").html("");
$("img").attr({ "src": "project/Images/processing.gif" });
$("#_fileForm").submit(function () {
$("#_fileForm").ajaxSubmit({
type: "post",
url: "project/help.aspx",
success: function (data1) {
var remsg = data1.split("|");
var name = remsg[1].split("/");
if (remsg[0] == "1") {
var type = name[4].substring(name[4].indexOf("."), name[4].length);
$("#msg").html("文件名:" + name[name.length - 1] + " --- " + remsg[2]);
switch (type) {
case ".jpg":
case ".jpeg":
case ".gif":
case ".bmp":
case ".png":
$("img").attr({ "src": remsg[1] });
break;
default:
$("img").attr({ "src": "project/Images/msg_ok.png" });
break;
}
} else {
$("#msg").html("文件上传失败:" + remsg[2]);
$("img").attr({ "src": "project/Images/msg_error.png" });
}
},
error: function (msg) {
alert("文件上传失败");
}
});
return false;
});
$("#_fileForm").submit();
}
3、服务端处理上传。
protected void Page_Load(object sender, EventArgs e)
{
try
{
HttpPostedFile postFile = Request.Files[0];
//开始上传
string _savedFileResult = UpLoadFile(postFile);
Response.Write(_savedFileResult);
}
catch(Exception ex)
{
Response.Write("0|error|上传提交出错");
}
}
public string UpLoadFile(HttpPostedFile str)
{
return UpLoadFile(str, "/UpLoadFile/");
}
public string UpLoadFile(HttpPostedFile httpFile, string toFilePath)
{
try
{
//获取要保存的文件信息
string filerealname = httpFile.FileName;
//获得文件扩展名
string fileNameExt = System.IO.Path.GetExtension(filerealname);
if (CheckFileExt(fileNameExt))
{
//检查保存的路径 是否有/结尾
if (toFilePath.EndsWith("/") == false) toFilePath = toFilePath + "/";
//按日期归类保存
string datePath = DateTime.Now.ToString("yyyyMM") + "/" + DateTime.Now.ToString("dd") + "/";
if (true)
{
toFilePath += datePath;
}
//物理完整路径
string toFileFullPath = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + toFilePath;
//检查是否有该路径 没有就创建
if (!System.IO.Directory.Exists(toFileFullPath))
{
Directory.CreateDirectory(toFileFullPath);
}
//得到服务器文件保存路径
string toFile = Server.MapPath("~" + toFilePath);
string f_file = getName(filerealname);
//将文件保存至服务器
httpFile.SaveAs(toFile + f_file);
return "1|" + toFilePath + f_file + "|" + "文件上传成功";
}
else
{
return "0|errorfile|" + "文件不合法";
}
}
catch (Exception e)
{
return "0|errorfile|" + "文件上传失败,错误原因:" + e.Message;
}
}
/// <summary>
/// 获取文件名
/// </summary>
/// <param name="fileNamePath"></param>
/// <returns></returns>
private string getName(string fileNamePath)
{
string[] name = fileNamePath.Split('\');
return name[name.Length - 1];
}
/// <summary>
/// 检查是否为合法的上传文件
/// </summary>
/// <param name="_fileExt"></param>
/// <returns></returns>
private bool CheckFileExt(string _fileExt)
{
string[] allowExt = new string[] { ".gif", ".jpg", ".jpeg", ".rar",".png" };
for (int i = 0; i < allowExt.Length; i++)
{
if (allowExt[i] == _fileExt) { return true; }
}
return false;
}
public static string GetFileName()
{
Random rd = new Random();
StringBuilder serial = new StringBuilder();
serial.Append(DateTime.Now.ToString("HHmmss"));
serial.Append(rd.Next(100, 999).ToString());
return serial.ToString();
}
4、运行defualt.aspx页面以后显示的效果是:
③ jquery 多图片预览
给你重新写了一个,直接拷贝到记事本另存为html就可以调试(Jquery是在线引用的)。
以下代码在IE8和FF下测试通过。
另:程序如果有什么问题可以HI我。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
//全局变量
var FileCount=0;//上传文件总数
//添加上传文件按钮
function addFile(obj)
{
var filePath=$(obj).prev().val();
var FireFoxFileName="";
//FireFox文件的路径需要特殊处理
if(window.navigator.userAgent.indexOf("Firefox")!=-1)
{
FireFoxFileName=filePath;
filePath=$(obj).prev()[0].files.item(0).getAsDataURL();
}
if(!checkFile(filePath,FireFoxFileName))
{
$(obj).prev().val("");
return;
}
if(filePath.length==0)
{
alert("请选择上传文件");
return false;
}
FileCount++;
//添加上传按钮
var html='<span>';
html+='<input id="f'+FileCount+'" name="'+FileCount+'" type="file"/>';
html+='<input type="button" value="添加" onclick="addFile(this)"/>';
html+='</span>';
$("#fil").append(html);
//添加图片预览
html='<li>';
html+='<img id="img'+(FileCount-1)+'" src="'+filePath+'" width="100" height="100" style="cursor:pointer;" alt="暂无预览" />';
html+='<br/>';
html+='<a href="#" name="img'+(FileCount-1)+'" onclick="DelImg(this)">删除</a>';
html+='</li>';
$("#ImgList").append(html);
}
//删除上传文件(file以及img)
function DelImg(obj)
{
var ID=$(obj).attr("name");
ID=ID.substr(3,ID.length-3);
$("#f"+ID).parent().remove();
$(obj).parent().remove();
return false;
}
//检查上传文件是否重复,以及扩展名是否符合要求
function checkFile(fileName,FireFoxFileName)
{
var flag=true;
$("#ImgList").find(":img").each(function(){
if(fileName==$(this).attr("src"))
{
flag=false;
if(FireFoxFileName!='')
{
alert('上传文件中已经存在\''+FireFoxFileName+'\'!');
}
else
{
alert('上传文件中已经存在\''+fileName+'\'!');
}
return;
}
});
//文件类型判断
var str="jpg|jpeg|bmp|gif";
var fileExtName=fileName.substring(fileName.indexOf(".")+1);//获取上传文件扩展名
if(FireFoxFileName!='')//fireFox单独处理
{
fileExtName=FireFoxFileName.substring(FireFoxFileName.indexOf(".")+1);
}
//alert(fileExtName);
if(str.indexOf(fileExtName.toLowerCase())==-1)
{
alert("只允许上传格式为jpg,jpeg,bmp,gif的文件。");
flag=false;
}
return flag;
}
</script>
<style type="text/css">
.fil
{
width:300px;
}
.fieldset_img
{
border:1px solid blue;
width:550px;
height:180px;
text-align:left;
}
.fieldset_img img
{
border:1px solid #ccc;
padding:2px;
margin-left:5px;
}
#ImgList li
{
text-align:center;
list-style:none;
display:block;
float:left;
margin-left:5px;
}
</style>
</head>
<body>
<p>上传预览图片:<br>
<div id="fil" class="fil">
<span>
<input id="f0" name="f0" type="file"/>
<input type="button" value="添加" onclick="addFile(this)"/>
</span>
</div>
</p>
<div id="ok">
<fieldset class="fieldset_img">
<legend>图片展示</legend>
<ul id="ImgList">
<!--li>
<img id="img1" width="100" height="100" style="cursor:pointer;">
<br/>
<a href="#" name="img1" onclick="DelImg(this)">删除</a>
</li-->
</ul>
</fieldset>
</div>
</body>
</html>
④ jsp页面实现图片预览,截取和上传
比较常用,而且简单易用的jquery-uploadify插件,支持带进度的多线程上传
用到的是flash的跨域上传模型,这里不用深究
基本文件大致包括
jquery-x.x.x.js
jquery.uploadify.x.js
uploadify.swf
uploadify.css
使用方式:
$(function(){
$("#fileId").uploadify({
width:42,
height:32,
swf:'js/uploadify.swf',
uploader:'upload.do;jsessionid=<%=session.getId()%>',
buttonImage:'image/movetophone_white.png',
fileSizeLimit:2048,
fileObjName:"imgFile",
method:'post',
removeCompleted:true,
fileTypeExts:"*.gif;*.jpg;*.png;*.jpeg;*.bmp",
onSelectError:function(file,errorCode,errorMsg){
alert("文件过大");
},
onUploadStart:function(file){
},
onUploadSuccess:function(file,data,response){
alert("上传完成");
},
onUploadError:function(file,errorCode,errorMsg){
alert(errorMsg);
}
});
});
<inputtype="file"id="fileId"/>
另,工程中需要引入commons-fileupload的包。
⑤ 用js、jquery如何实现上传图片的预览
$("#btnLoadPhoto").upload({ url: "../UploadForms/RequestUpload.aspx?action=photo", type: "json", callback: calla });
//获得表单元素
HttpPostedFile oFile = context.Request.Files[0];
//设置上传路径
string strUploadPath = "temp/";
//获取文件名称
string fileName = context.Request.Files[0].FileName;
补充:JQuery是继prototype之后又一个优秀的Javascript库。它是轻量级的js库 ,它兼容CSS3,还兼容各种浏览器(IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+),jQuery2.0及后续版本将不再支持IE6/7/8浏览器。jQuery使用户能更方便地处理HTML(标准通用标记语言下的一个应用)、events、实现动画效果,并且方便地为网站提供AJAX交互。jQuery还有一个比较大的优势是,它的文档说明很全,而且各种应用也说得很详细,同时还有许多成熟的插件可供选择。jQuery能够使用户的html页面保持代码和html内容分离,也就是说,不用再在html里面插入一堆js来调用命令了,只需要定义id即可。
⑥ 我需要一个js或者jquery能批量上传图片+预览的功能。急~~~急~~~急~~
WebUploader项目,符合你的要求。
//文件上传过程中创建进度条实时显示。
uploader.on('uploadProgress',function(file,percentage){
var$li=$('#'+file.id),
$percent=$li.find('.progressspan');
//避免重复创建
if(!$percent.length){
$percent=$('<pclass="progress"><span></span></p>')
.appendTo($li)
.find('span');
}
$percent.css('width',percentage*100+'%');
});
//文件上传成功,给item添加成功class,用样式标记上传成功。
uploader.on('uploadSuccess',function(file){
$('#'+file.id).addClass('upload-state-done');
});
//文件上传失败,显示上传出错。
uploader.on('uploadError',function(file){
var$li=$('#'+file.id),
$error=$li.find('div.error');
//避免重复创建
if(!$error.length){
$error=$('<divclass="error"></div>').appendTo($li);
}
$error.text('上传失败');
});
//完成上传完了,成功或者失败,先删除进度条。
uploader.on('uploadComplete',function(file){
$('#'+file.id).find('.progress').remove();
});
更多细节,请查看js源码。
⑦ js/jquery如何实现一张图片的上传预览功能。。。。
使用AJAX,把文件保存到临时目录,把返回的值(文件路径),放到页面上预先添加的<IMG> 标签中,就可显示预览图片,再点上传才把文件从临时目录(删除临时目录文件)复制到你指定的目录中
⑧ web前端上传图片的几种方法
下面给你介绍3种web前端上传图片的方法:
1.表单上传
最传统的图片上传方式是form表单上传,使用form表单的input[type=”file”]控件,打开系统的文件选择对话框,从而达到选择文件并上传的目的。
ajax无刷新上传
Ajax无刷新上传的方式,本质上与表单上传无异,只是把表单里的内容提出来采用ajax提交,并且由前端决定请求结果回传后的展示结果。
3.各类插件上传
当上传的需求要求可预览、显示上传进度、中断上传过程、大文件分片上传等等,这时传统的表单上传很难实现这些功能,我们可以借助现有插件完成。
如网络上传插件Web Uploader、jQuery图片预览插件imgPreview 、拖拽上传与图像预览插件Dropzone.js等等,大家可根据项目实际需求选择适合的插件。
⑨ 怎样用js或者jq实现点击这个图片就可以选择上传还有预览图片啊
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<h3>请选择图片文件:JPG/GIF</h3>
<form name="form0" id="form0" >
<input type="file" name="file0" id="file0" multiple="multiple" />
<br><br><img src="" id="img0" width="120">
</form>
</body>
<script>
$("#file0").change(function(){
var objUrl = getObjectURL(this.files[0]) ;
console.log("objUrl = "+objUrl) ;
if (objUrl)
{
$("#img0").attr("src", objUrl);
$("#img0").removeClass("hide");
}
}) ;
//建立一个可存取到该file的url
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) ;
}
return url ;
}
$('input').on('change',function(){
var value = $(this).val();
value = value.split("\\")[2];
alert(value);
})
</script>
</html>
⑩ ASP.NET上传图片。上传图片前想先在窗口中生成图片的预览,最后再决定是否上传。请高手提供下思路。
上传之前预览的是本地图象!
也就是说,img的路径设为file:///C:/xx.jpg,而上传后的图片是网络图片,也就是说路径不再是本地了!技术的难点在就这于如何取出图片的长宽,并安比例显示,这种情况下是有一定的难度的。否则是很容易的!