无刷新文件上传 利用iframe实现
效果如图:
示例是基于asp.net mvc实现的
html代码:
<form id="form2" name="form2" class="form-horizontal" enctype="multipart/form-data" action="UploadIcon" method="post" target="ajaxUpload"> <div class="form-group"> <label for="inputIcon" class="col-sm-2 control-label">头像</label> <div class="col-sm-5"> <input type="file" id="inputIcon" name="icon" accept="image/*" placeholder="路径" onchange="uploadFile()"> <iframe name="ajaxUpload" frameborder="0" width="100px" height="100px"></iframe> </div> </div> </form>
需要一个页面UploadIcon.cshtml:
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> </head> <body> <img alt="" width="50px" height="50px" src="@ViewData["iconPath"]" /> </body> </html>
JS代码:
function uploadFile() { $('#form2').submit(); }
C#代码:
public ActionResult UploadIcon() { string fileName = Request.Files["icon"].FileName; string filePath = "/Data/UserIcon/Temp/" + Guid.NewGuid() + fileName.Substring(fileName.LastIndexOf('.')); Request.Files["icon"].SaveAs(Server.MapPath(filePath)); ViewData["iconPath"] = filePath; return View(); }
作者:sy
出处:http://www.cnblogs.com/sydeveloper
QQ:522733724
本页版权归作者和博客园所有,欢迎转载,但未经作者同意必须保留此段声明,
且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利