关于Ajax实现无刷新上传头像
首先我们改造我们的 那个上传的 <input>
<tr><td>头像:</td><td>
<form id="imageform" method="post" action="Upload.ashx" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上传" onclick="return checkfile(imageform.file.value);" />
</form>
</td><td></td></tr>
最新的项目结构
这个就是我们改好的了,因为上传 需要的提交方式是 POST,所以我们只能,临时搭建一个POST了 ,呵呵
<form id="imageform" method="post" action="Upload.ashx" enctype="multipart/form-data"> 主要 要注意这一句啊。
enctype 注意 一定要是 我写的这种类型哦。 提交页面我们是 Upload.ashx 这个页面,所以你需要新创建一个界面接收我们的数据哦。
呵呵,上面的那个 onclick="getsex(this.value);" 其实就是一个非空验证
function checkfile(value) {
if (value == '') {
alert('请选择文件!');
imageform.file.focus();
return false;
}
}
好了,我们下面实现一个最简陋的版本,无刷新上传 头像,呵呵
<tr><td>头像:</td><td>
<form id="imageform" method="post" action="Upload.ashx" enctype="multipart/form-data" target="submitIform">
<input type="file" name="file" />
<input type="submit" value="上传" onclick="return checkfile(imageform.file.value);" />
</form>
</td><td></td></tr>
<tr><td colspan=3 ><img style="width:150px; height:150px;" src="###" id="image"/></td></tr>
修改一下我们的前台现实 头像的代码。
注意一个特别的地方,这也算是无刷新上传的一个小技巧吧 ,就是这个 target="submitIform"
这个地方一定要提交到, <iframe name="submitIform" style="display:none;"></iframe>
当然,你有其他的办法更好,我这里主要是,一会后台调用JS事件,好实现,调用父窗体的事件。提交这个隐藏的 IFROM中,也算是一种特别的方式吧。
前台新增加实时显示图片的方法
if (fileName == '') {
alert('没有上传文件');
return false;
}
document.getElementById('image').src = 'Upload/'+fileName;
}好了,基本的工作,我们已经做完了,下面,就是,我们的 Upload.ashx的代码了 public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
context.Response.ContentType = "utf-8";
HttpPostedFile file = context.Request.Files["file"];
string error = null;
if (file == null || file.ContentLength <= 0) {
error = "请选择需要上传的图片";
}
else
{
string newFileName = Guid.NewGuid().ToString();
var extension = Path.GetExtension(file.FileName).ToUpper();
newFileName += extension;
string filePath = string.Empty;
if (SaveAsTemp(newFileName, file, context))
{
context.Response.Write("<script>parent.uploadOver('" + newFileName + "')</script>"); }
}
}
context.Response.Write("<script>parent.uploadOver('" + newFileName + "')</script>"); 我想这句你就知道,我上面的那个 为什么要用IF嵌套了,呵呵。SaveAsTemp
这个方法是我们的 Save 图片的方法
public bool SaveAsTemp(string fileName, HttpPostedFile file,HttpContext context)
{
HttpServerUtility Server = context.Server;
try
{
string filePath = Server.MapPath("~/Upload/" + fileName);
file.SaveAs(filePath);
return true;
}
catch
{
fileName = null;
return false;
}
}
本文出自:DIY博客园,链接:https://www.diybloghome.com/frontlogy/171.html,转载请注明!