先引入文中所用的文件,下载地址为:
https://download.csdn.net/download/xuejunling/10360702
引入两个js, 一个样式
View:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
<link rel="stylesheet" href="/layui/css/layui.css" media="all">
@*<script src="/Scripts/jquery-1.12.4.min.js"></script>*@
<script src="/Scripts/jquery-1.8.2.min.js"></script>
<script src="/Scripts/jquery.form.js"></script>
</head>
<body style="margin:0;padding:0;">
@using (Ajax.BeginForm("UpLoadLogo_Post", "Default",
new { },
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
AllowCache = false
}, new { enctype = "multipart/form-data", id = "myForm" }))
{
<div class="layui-form-item">
<div class="layui-inline">
<div class="layui-input-inline" style="width: 200px;">
@Html.TextBox("file", "", new { type = "file", required = "required", multiple = "multiple",style="width:200px;" })
</div>
<div class="layui-input-inline" style="width:50px;">
<input type="submit" value="上传" />
</div>
<div class="layui-input-inline" style="width:100px;">
<div class="bar"></div>
<div class="percent" style="padding-top:5px; display:none;">0%</div>
</div>
</div>
</div>
}
</body>
</html>
<script>
(function () {
var bar = $(".bar");
var percent = $(".percent");
var status = $("#status");
//以下的js ,加入了上传进度的判断, 我在页面中注释了,不要这功能了,如果需要 ,可以把上面的隐藏id显示出来。
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
$(".progress").attr("display", "display");
var percentVal = percentComplete + '%';
bar.width(percentVal);
bar.attr("background-color", "#00ff21");
percent.html(percentVal);
},
success: function (data) {
var percentVal = '100%';
bar.width(percentVal);
percent.attr("background-color", "#00ff21");
percent.html(percentVal);
if (data && data.Error == "0") {
//此上传功能可以作为一个单独的模块来使用,在需要有上传的页面中加入<iframe>标签即可。
以下是找到父窗口中的对应的id, 当上传成功时,向其传值 。
parent.document.getElementById('logo').value = data.Data;
parent.document.getElementById('showlogo').innerHTML = "<img src='" + data.Data + "' width='50' height='50' />";
} else {
parent.document.getElementById('showlogo').innerHTML = data.Message;
}
},
complete: function (xhr) {
$(".progress").attr("display", "none");
status.html(xhr.responseText);
}
});
})();
</script>
后台:
[HttpGet]
public ActionResult UpLoadLogo(string id)
{
return View();
}
[HttpPost]
public ActionResult UpLoadLogo_Post()
{
if (Request.Files != null && Request.Files.Count > 0)
{
float contextlength = 1024 * 1024 * 3;
float.TryParse(upload_contentlength, out contextlength);
HttpPostedFileBase file = Request.Files[0];
if (file.ContentLength == 0)
{
return Json(new { Error = 1, Message = "请选择上传的文件!" });
}
if (file.ContentLength > contextlength)
{
return Json(new { Error = 1, Message = "上传文件过大,不能超过" + contextlength / (1024 * 1024 * 1.0) + "M!" });
}
string extension = System.IO.Path.GetExtension(file.FileName);
string oldfilename = Path.GetFileName(file.FileName);
string now = DateTime.Now.ToString("yyyyMMdd");
string guid = Guid.NewGuid().ToString("N");
Random r = new Random();
int n = r.Next(1000, 9999);
string newfilename = string.Concat(guid, n, extension);
string dirpath = string.Format("/{0}/{1}", upload_userlogo, now);
if (!Directory.Exists(Server.MapPath(dirpath)))
{
Directory.CreateDirectory(Server.MapPath(dirpath));
}
string uploadfilepath = Path.Combine(Server.MapPath(dirpath), newfilename);
file.SaveAs(uploadfilepath);
//IsAllowedExtension判断文件是否是真实的图片文件,如果是上传成功,如果不是,则删除
//特别提示:为了安全,服务器的上传文件夹,一定要去除执行脚本的权限,这样即使上传了木马程序,也不能运行,具体操作,可以网上搜索一下,这里简单提供一下如何做,把上传图片所在的文件夹里新建一个web.config文件,里面写入以下内容即可。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<handlers accessPolicy="Read" />
</system.webServer>
</configuration>
以上是小插曲,为了安全,还是重视点好。
if (IsAllowedExtension(uploadfilepath))
{
string filepath = dirpath + "/" + newfilename;
return Json(new { Error = 0, Data = filepath });
}
else
{
if (System.IO.File.Exists(uploadfilepath))
{
System.IO.File.Delete(uploadfilepath);
}
return Json(new { Error = 1, Message = "请上传jpg,png,gif等类型的图片!" });
}
}
else
{
return Json(new { Error = 1, Message = "请选择要上传的图片!" });
}
}
//检测真实图片格式。
public static bool IsAllowedExtension(string path)
{
System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
try
{
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
}
catch
{
}
r.Close();
fs.Close();
//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
if (fileclass == "255216" || fileclass == "7173" || fileclass == "13780")
{
return true;
}
else
{
return false;
}
}
其中:
upload_contentlength :设定的上传文件的大小。
upload_userlogo: 上传文件放置的文件夹。