???笨小孩通过本文主要向大家介绍了文件下载 asp.net,文件上传 asp.net,多文件上传 asp.net,js调用asp.net方法,asp.net等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
本文实例为大家分享了ASP.NET 文件上传,供大家参考,具体内容如下
1、最近应项目开发的需求要实现附件的异步上传和下载。
2、上传:文件上传到指定的路径下,并返回上传文件的信息给前端界面,如:文件的图标、上传的文件名、文件的大小。
3、上传后,在前端界面上显示上传的文件信息,点击文件名实现将上传的文件下载到本地。
4、先展示一下Demo运行的效果图:

点击提交后:

点击文件名实现下载到本地:

5、下面就给出前台代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax Form - jQuery EasyUI Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<h2>Ajax Form Demo</h2>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
<div>Type in input box and submit the form.</div>
</div>
<div class="easyui-panel" title="Ajax Form" style="width:300px;padding:10px;">
<form id="ff" action="api/Loding" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>Name:</td>
<td><input name="name" class="f1 easyui-textbox"></input></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" class="f1 easyui-textbox"></input></td>
</tr>
<tr>
<td>Phone:</td>
<td><input name="phone" class="f1 easyui-textbox"></input></td>
</tr>
<tr>
<td>File:</td>
<td><input name="file" class="f1 easyui-filebox"></input></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="提交"></input></td>
</tr>
</table>
<input type="text" value="LodingTable" name="tableName" hidden="hidden" />
</form>
</div>
<div>
<img id="img" src="" width="20" height="20" />
<a id="downLoad" downloadid="0" href="#"></a>
<label>文件大小:</label>
<label class="size"></label><button id="delete">删除</button>
<button id="loding">导入1</button>
</div>
<style scoped>
.f1 {
width: 200px;
}
</style>
<script type="text/javascript">
$(function () {
$("#loding").hide();
$("#delete").hide().click(function () {
alert("删除文件");
});
$("#loding").click(function () {
var tUrl = '/api/Loding/Get';
//var tJsonStr = '{"idInventoryPrice":"4","withdrawDetails":[{"cInvCode":"800487","cInvCodeSub":"00","iConverDiscount":"0","iUnitPrice":"9.9","iSalePrice":"9.9"},{"cInvCode":"800689","cInvCodeSub":"00","iConverDiscount":"0","iUnitPrice":"6.5","iSalePrice":"5.9"}]}';
$.ajax({
type: "Get",
url: tUrl,
dataType: "json",
async: false,
success: function (data) {
alert(JSON.stringify(data));
}
});
});
$('#ff').form({
success: function (data) {
var json = JSON.parse(data);
if (json.result == 1) {
$("#delete").show();
$("#img").attr("src", json.details[0].AttachmentNameTypeICO);
$("#downLoad").attr("downloadid", json.details[0].ID); $("#downLoad").html(json.details[0].AttachmentName);
$(".size").html(json.details[0].AttachSize + "KB");
var tUrl = 'http://localhost:11703/api/Loding/DownLoad?ID=' + $("#downLoad").attr("downloadid");
$("#downLoad").attr("href", tUrl);
}
else {
alert(json.resultdetail);
}
}
});
});
</script>
</body>
</html>
</div>
6、后台上传代码:
NameValueCollection nvf = HttpContext.Current.Request.Form;
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string tempPath = "/Upload/" + DateTime.Now.ToString("yyyy-MM-dd/");
string fileSaveLocation = HttpContext.Current.Server.MapPath("~" + tempPath);//附件的保存地址
Dictionary<string, object> dic = new Dictionary<string, object>();
if (!Directory.Exists(fileSaveLocation))
{
Directory.CreateDirectory(fileSaveLocation);
}
CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
try
{
var result = await Request.Content.ReadAsMultipartAsync(provider).ContinueWith<Dictionary<string, object>>(x =>
{
var file = provider.FileData[0];
FileInfo fileinfo = new FileInfo(file.LocalFileName);
if (fileinfo.Length <= 0)
{
dic.Add("result", -1);
dic.Add("resultdetail", "未上传文件");
}
else
{
double? filelength = fileinfo.Length / 1024.0;
if (filelength > 10 * 1024)
{
dic.Add("result", -1);
dic.Add("resultdetail", "上传文件不能大于10M");
}
else
{
string saveFileName = Guid.NewGuid().ToString() + fileinfo.Extension;
fileinfo.CopyTo(Path.Combine(fileSaveLocation, saveFileName), true);
fileinfo.Delete();
dic.Add("result", 1);
dic.Add("resultdetail", "上传成功");
dic.Add("realPath", file.LocalFileName);//附件保存的绝对路径
dic.Add("attachmentType", fileinfo.Extension);//附件类型
dic.Add("attachmentName", Path.GetFileName(file.LocalFileName));//上传的附件名
dic.Add("attachSize", Convert.ToInt32(filelength));//附件大小KB
dic.Add("aealPath", tempPath + saveFileName);//附件保存相对路径
}
}
return dic;
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (Exception ex)
{
return HandleJson.ToJson(ex.ToString(), false);
}
var isSuccess = dic["result"].TryToInt() == 1;
var msg = dic["resultdetail"].TryToString();//返回上传信息
var realPath = string.Empty;//附件保存的绝对路径
var relativePath = string.Empty;//返回相对路径
var AttachSize = 0;//文件大小kB
var AttachmentType = string.Empty;//文件扩展名
var AttachmentName = string.Empty;//原文件名
if (isSuccess)
{
realPath = dic["realPath"].TryToString();
relativePath = dic["aealPath"].TryToString();
AttachSize = dic["attachSize"].TryToInt();
AttachmentType = dic["attachmentType"].TryToString();
AttachmentName = dic["attachmentName"].TryToString();
}
StringBuilder sql = new StringBuilder();
if (isSuccess)
{
try
{
#region 获取图标路径
var ICOPath = string.Empty;
sql.Append(@"SELECT * FROM dbo.AttachmentType(NOLOCK) WHERE AttachmentType=@AttachmentType");
var ICOTable = Common.HandleSQL.GetData(sql.ToString(), null, new SqlParameter[] { new SqlParameter("@AttachmentType", AttachmentType) });
if (ICOTable.Rows.Count <= 0)
{
ICOPath = "";
}
else
{
ICOPath = ICOTable.Rows[0]["AttachmentNameTypeICO"].ToString();
}
#endregion 获取图标路径
#region 保存上传记录
sql.Cl

