C# 数据上传(自用笔记)
#region 数据上传
[HttpPost]
public ActionResult UploadFile()
{
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase file = files["file"];
string guid = Guid.NewGuid().ToString();
string txt = string.Empty;
string path = "";
if (file != null && file.ContentLength > 0)
{
string fileName = file.FileName;
//判断文件名字是否包含路径名,如果有则提取文件名
if (fileName.LastIndexOf("\\") > -1)
{
fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
}
bool b = false;
string lastname = string.Empty;
string fileNamelast= string.Empty;
if (fileName.LastIndexOf('.') > -1)
{
string[] strName = fileName.Split('.');
fileNamelast = strName[0];
lastname = fileName.Substring(fileName.LastIndexOf('.')).ToLower();
if (!(lastname == "jpeg" || lastname.ToLower() == "pdf" || lastname == "jpg" || lastname == "rar" || lastname == "zip" || lastname == "doc" || lastname == "docx" || lastname == "xls" || lastname == "xlsx" || lastname == "pdf" || lastname == "zip"))
b = true;
}
if (b)
{
if (!System.IO.Directory.Exists(@"" + ConfigModel.uploadpath + ""))
{
System.IO.Directory.CreateDirectory(@"" + ConfigModel.uploadpath + "");//不存在就创建目录
}
path = ConfigModel.uploadpath + fileNamelast + guid + lastname;
try
{
file.SaveAs(path);
}
catch (Exception e)
{
txt = "异常:" + e.Message;
}
}
else
txt = "文件格式有误";
}
else
txt = "没有可用数据";
if (string.IsNullOrEmpty(txt))
return ToJson(1, path, "上传成功!");
else
return ToJson(-1, "操作异常", txt);
}
#endregion
//前台JS:
//上传:
,
HuploadifyDo: function () {
/// <summary>
/// 初始化上传
/// </summary>
var url = "";
$('#upload').Huploadify({
fileSizeLimit: 5 * 1024,
uploader: "/FinancialRecord/UploadFile", //url
onUploadComplete: function (data, txt) {
layer.closeAll();
//$("#infolbl").html("");
//$("#hBath").val("");
var r = eval('(' + txt + ')');
if (r.result == 1) {
FinancialRecordIndex.PATH = r.data; //赋值
$("#lblpath").text(FinancialRecordIndex.PATH);
} else {
LayerShowErr(r.desc);
}
},
onUploadStart: function () {
FinancialRecordIndex.WiteDo("上传中,请勿关闭!", 0);
}
});
}
,
WiteDo: function (_a, _b) {
/// <summary>
/// 初始化等待
/// </summary>
/// <param name="_a" type="type"></param>
/// <param name="_b" type="type"></param>
if (_b == 0) {
var htmltxt = '<div style="width:330px;height:160px;text-align:center"><div style="height:5px"> </div><div class="panel-body"><div class="sk-folding-cube">';
htmltxt += '<div class="sk-cube1 sk-cube"></div>';
htmltxt += '<div class="sk-cube2 sk-cube"></div>';
htmltxt += '<div class="sk-cube4 sk-cube"></div>';
htmltxt += '<div class="sk-cube3 sk-cube"></div>';
htmltxt += ' </div>';
htmltxt += '</div><span id="witeInfo" style="font-size:12px;color:#1ab394">' + _a + '</span></div>';
layer.open({
type: 1,
title: false,
closeBtn: 0,
shadeClose: false,
content: htmltxt
});
} else {
$("#witeInfo").html(_a);
}
}
视图页面引用:
<script src="~/Scripts/js/plugins/Huploadify/jquery.Huploadify.js"></script>
<link href="~/Scripts/js/plugins/Huploadify/Huploadify.css" rel="stylesheet" />