这个并不是那么简单做出来的,一般情况下会加一段iframe代码,模拟ajax上传。
代码很简单,如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=utf-8" />
<title>By:DragonDean</title>
<script type="text/javascript">
//下面用于图片上传预览功能
function setImagePreview(avalue) {
var docObj=document.getElementById("doc")
var imgObjPreview=document.getElementById("preview")
if(docObj.files &&docObj.files[0])
{
//火狐下,直接设img属性
imgObjPreview.style.display = 'block'
imgObjPreview.style.width = '150px'
imgObjPreview.style.height = '180px'
//imgObjPreview.src = docObj.files[0].getAsDataURL()
//火狐7以上版本不能用上面的getAsDataURL()方式获取,需要一下方式
imgObjPreview.src = window.URL.createObjectURL(docObj.files[0])
}
else
{
//IE下,使用滤镜
docObj.select()
var imgSrc = document.selection.createRange().text
var localImagId = document.getElementById("localImag")
//必须设置初始大小
localImagId.style.width = "150px"
localImagId.style.height = "180px"
//图片异常的捕捉,防止用户修改后缀来伪造图片
try{
localImagId.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)"
localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc
}
catch(e)
{
alert("您上传的图片格式不正确,请重新选择!")
return false
}
imgObjPreview.style.display = 'none'
document.selection.empty()
}
return true
}
</script>
</head>
<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td height="101" align="center">
<div id="localImag"><img id="preview" src="http://blog.chuangling.net/Public/images/top.jpg" width="150" height="180" style="display: blockwidth: 150pxheight: 180px"></div>
</td>
</tr>
<tr>
<td align="center" style="padding-top:10px"><input type="file" name="file"
id="doc" style="width:150px" onchange="javascript:setImagePreview()"></td>
</tr>
</tbody>
</table>
</body>
</html>
如果只是上传的话那太容易了,如果还要显示那就难了,因为要显示的话就不能只向服务器提交一次请求,必须异步提交。下面的例子是我亲自写的,异步提交上传图片并预览。全部代码都在。
首先建一个html文件,复制以下html文本。使用说明:
引用jquery两个js文件,网上自己搜吧,到处都有。
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
2.添加两个文本框,第一个ID必须是“bigImage1”,第二个必须是“smallbigImage1”。
<input type="text" name="url1" id="bigImage1" style="width:150px" onclick="selectImage(this)" />
<input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />
当点击第一个文本框时,d出一个上传窗口,选择一张图片并点“上传”,上传成功后可预览图片。此过程会在服务器上把原图片生成一张缩略图,并把原图URL和缩略图URL一起以JSON格式返回到前台页面,临时显示缩略图。当点击“确定”时,它会把两个URL添加到两个对应ID的文本框。第二个框是隐藏的,给用户的感觉就像是只返回一个URL一样。
3.请自己写脚本[document.getElementById("bigImage1").value] 获得两个文本框的值,再进行你想做的 *** 作。
4.id为"uploadDiv"的DIV是一个整体,不可分割。主要是提供一个文件类型的表单,用于异步上传。请修改action的URL为你上传的后台路径。
下面是HTML代码
<!DOCTYPE html><html>
<head>
<title>Index</title>
<script src="jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="jquery.form.js" type="text/javascript"></script>
<script type="text/javascript">
function selectImage(obj) {
var inputId = obj.id
document.getElementById('btnSure').setAttribute('inputId', inputId)
var x = window.event.x
var y = window.event.y
var uploadDiv = document.getElementById('uploadDiv')
uploadDiv.style.left = x + 10 + 'px'
uploadDiv.style.top = y + 10 + 'px'
uploadDiv.style.position = 'fixed'
uploadDiv.style.display = 'inline'
}
function closeDiv() {
document.getElementById('btnSure').style.display = 'none'
document.getElementById('showImage').style.display = 'none'
document.getElementById('uploadDiv').style.display = 'none'
}
function makeSure(obj) {
var inputId = obj.getAttribute('inputId')
document.getElementById(inputId).value = document.getElementById('showImage').getAttribute('big')
document.getElementById('small' + inputId).value = document.getElementById('showImage').getAttribute('small')
document.getElementById('image' + inputId).src = document.getElementById('showImage').getAttribute('small')
document.getElementById("btnSure").style.display = 'none'
document.getElementById('showImage').style.display = 'none'
document.getElementById('uploadDiv').style.display = 'none'
}
$(function () {
//异步上传图片
$('#btnUpload').click(function () {
if ($('#upImage').val() == '') {
alert('请选择一张图片文件')
return
}
$('#fileForm').ajaxSubmit({
success: function (msg) {
var strJSON = msg //得到的JSON
var image = eval("(" + strJSON + ")") //转换后的JSON对象
document.getElementById('uploading').style.display = 'none'
$('#showImage').css('display', 'inline')
$('#showImage').attr('src', image.big)
$('#showImage').attr('big', image.big)
$('#showImage').attr('small', image.small)
$('#btnSure').css('display', 'inline')
}
})
document.getElementById('uploading').style.display = 'block'
})
})
</script>
</head>
<body>
<p>上传单个文件或图片</p>
<div>
<input type="text" name="url1" id="bigImage1" style="width:150px" onclick="selectImage(this)" />
<input type="hidden" name="smallUrl1" id="smallbigImage1" value="" />
</div>
<div id="uploadDiv" style="width: 400px height: 280px border: 1px solid #9eb9f1
background-color: #e1eaea text-align:left display:none z-index:999">
<div>
<div style="width: 376px float: left padding-left:4px padding-top:4px padding-bottom:4px overflow:hidden">
<form id="fileForm" method="post" action="/Home/UploadImage" enctype="multipart/form-data" >
<input type="file" id="upImage" name="upImage" style="padding-bottom: 1px padding-left: 8px
padding-right: 8px height: 24px width:220px padding-top: 1px" />
<input type="button" id="btnUpload" value="上传" style="padding-bottom: 1px padding-left: 8px padding-right: 8px
height: 24px cursor: pointer padding-top: 1px line-height: 12px" />
<span id="uploading" style="color:#ff0000 display:none font-size:14px font-weight:bold">上传中......</span>
<input type="button" id="btnSure" value="确定" style="padding-bottom: 1px padding-left: 8px padding-right: 8px
height: 24px cursor: pointer padding-top: 1px line-height: 12px display:none background-color:#9fd0f9" onclick="makeSure(this)" />
</form>
</div>
<div style="width: 20px height: 30px float: right ">
<div style="width: 20px height: 20px background-color:#9fc0f7 font-size:20px text-align:center line-height:16px cursor:pointer" onclick="closeDiv()">X</div>
</div>
</div>
<div style="width:398px height:240px text-align:center overflow:hidden ">
<img id="showImage" alt="预览图片" src="" style="width: 340px display:none" />
</div>
</div>
</body>
</html>
下面是后台代码
返回到前台页面的JSON格式对象是以类的对象。public class ReturnImage
{
public string big { get set }
public string small { get set }
public string isSuccessfull { get set }
public string message { get set }
}
对于上传和生成缩略图,请自行完成,以下是ASP.NET MVC的例子。
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View()
}
/// <summary>
/// 上传图片
/// </summary>
/// <returns></returns>
public ActionResult UploadImage()
{
//定义错误消息
JsonResult msg = new JsonResult()
try
{
//接受上传文件
HttpPostedFileBase postFile = Request.Files["upImage"]
if (postFile != null)
{
DateTime time = DateTime.Now
//获取上传目录 转换为物理路径
string uploadPath = Server.MapPath("~/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/")
//文件名
string fileName = time.ToString("yyyyMMddHHmmssfff")
//后缀名称
string filetrype = System.IO.Path.GetExtension(postFile.FileName)
//获取文件大小
long contentLength = postFile.ContentLength
//文件不能大于2M
if (contentLength <= 1024 * 2048)
{
//如果不存在path目录
if (!Directory.Exists(uploadPath))
{
//那么就创建它
Directory.CreateDirectory(uploadPath)
}
//保存文件的物理路径
string saveFile = uploadPath + fileName + "_big" + filetrype
try
{
//保存文件
postFile.SaveAs(saveFile)
//保存缩略图的物理路径
string small = uploadPath + fileName + "_small" + filetrype
MakeThumbnail(saveFile, small, 320, 240, "W")
ReturnImage image = new ReturnImage()
image.big = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_big" + filetrype
image.small = "/UploadFiles/" + time.Year + "/" + time.ToString("yyyyMMdd") + "/" + fileName + "_small" + filetrype
msg = Json(image)
}
catch
{
msg = Json("上传失败")
}
}
else
{
msg = Json("文件大小超过限制要求")
}
}
else
{
msg = Json("请选择文件")
}
}
catch (Exception e)
{
}
msg.ContentType = "text/html"
return msg
}
/// <summary>
由于回答超过最大限制,/// 生成缩略图 的代码请向我索取
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)