无刷新文件上传 利用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();
}

 

posted @ 2014-04-21 17:55  飛雲若雪  阅读(1682)  评论(2编辑  收藏  举报