欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET文件上传Upload的实现方法

程序员文章站 2022-10-15 08:30:42
本文实例为大家分享了asp.net 文件上传,供大家参考,具体内容如下 1、最近应项目开发的需求要实现附件的异步上传和下载。 2、上传:文件上传到指定的路径下,并返回上...

本文实例为大家分享了asp.net 文件上传,供大家参考,具体内容如下

1、最近应项目开发的需求要实现附件的异步上传和下载。

2、上传:文件上传到指定的路径下,并返回上传文件的信息给前端界面,如:文件的图标、上传的文件名、文件的大小。

3、上传后,在前端界面上显示上传的文件信息,点击文件名实现将上传的文件下载到本地。

4、先展示一下demo运行的效果图:

ASP.NET文件上传Upload的实现方法

点击提交后:

ASP.NET文件上传Upload的实现方法

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

ASP.NET文件上传Upload的实现方法

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> 

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.clear();
   sql.append(@"declare @id int
select @id=max(id)+1 from dbo.attachment(nolock)
if(@id is null)
begin
set @id=1
end
insert into dbo.attachment
 ( id ,
  attachmentname ,
  attachmenttype ,
  realpath ,
  attachsize ,
  uploaddate ,
  uploadperson ,
  uploadipaddress
 )
values ( @id , -- id - int
  @attachmentname , -- attachmentname - nvarchar(max)
  @attachmenttype , -- attachmenttype - nvarchar(50)
  @realpath , -- realpath - nvarchar(max)
  @attachsize , -- attachsize - bigint
  getdate() , -- uploaddate - datetime
  @uploadperson , -- uploadperson - nvarchar(50)
  @uploadipaddress -- uploadipaddress - varchar(50)
 )
select * from dbo.attachment(nolock) where id=@id;
");
   sqlparameter[] paras = new sqlparameter[] { new sqlparameter("@attachmentname", attachmentname),
   new sqlparameter("@attachsize", attachsize), new sqlparameter("@realpath", relativepath),
   new sqlparameter("@attachmenttype", attachmenttype),new sqlparameter("@uploadperson","魏小伟"),new sqlparameter("@uploadipaddress",handlelog.getipaddress()) };
   var insert = getdata(sql.tostring(), null, paras);
   insert.columns.add("attachmentnametypeico", typeof(string));
   insert.rows[0]["attachmentnametypeico"] = icopath;
   int id = convert.toint32(insert.rows[0]["id"].tostring());//上传附件的id
   return handlejson.tojson(insert, 0);

   #endregion 保存上传记录
  }
  catch (exception ex)
  {
   if (system.io.file.exists(realpath))
   {
   file.delete(realpath);
   }
   return handlejson.tojson(ex.tostring(), false);
  }
  }
  else
  {
  return handlejson.tojson(msg, false);
  }

7、下载代码:

[httpget, route("api/loding/download")]
 public httpresponsemessage download()
 {
  #region 获取界面参数

  namevaluecollection nvc = httpcontext.current.request.querystring;
  int id = nvc["id"].trytoint();
  if (id <= 0)
  {
  return handlejson.tojson("传入参数错误", false);
  }

  #endregion 获取界面参数

  #region sql

  stringbuilder sql = new stringbuilder();
  sql.append(@"select * from dbo.attachment(nolock) where id=@id ");

  #endregion sql

  #region 执行sql

  var dt = handlesql.getdata(sql.tostring(), null, new sqlparameter[] { new sqlparameter("@id", id) });
  if (dt.rows.count <= 0)
  {
  return handlejson.tojson("未找到下载文件", false);
  }
  var filepath = httpcontext.current.server.mappath("~" + dt.rows[0]["realpath"].trytostring());//下载文件的绝对路径
  string filename = dt.rows[0]["attachmentname"].trytostring();//下载的文件名

  #endregion 执行sql

  #region 下载文件并添加下载记录

  try
  {
  //var filepath = system.web.hosting.hostingenvironment.mappath(@"~/download/" + filename);
  var stream = new filestream(filepath, filemode.open);
  httpresponsemessage response = new httpresponsemessage(httpstatuscode.ok);
  response.content = new streamcontent(stream);
  response.content.headers.contenttype = new mediatypeheadervalue("application/octet-stream");
  response.content.headers.contentdisposition = new contentdispositionheadervalue("attachment")
  {
   filename = filename
  };

  #region 添加下载记录

  sql.clear();
  sqlparameter[] paras = new sqlparameter[] { new sqlparameter("@id", id), new sqlparameter("@downloadperson", "魏小伟"), new sqlparameter("@downloadip", handlelog.getipaddress()) };
  sql.append(@"declare @autoid int
select @autoid=max(autoid)+1 from dbo.attachmentdowloadlog(nolock)
if(@autoid is null)
begin
set @autoid=1
end
insert into dbo.attachmentdowloadlog
 ( autoid ,
  id ,
  downloadperson ,
  downloaddate ,
  downloadip
 )
values ( @autoid , -- autoid - int
  @id , -- id - int
  @downloadperson , -- downloadperson - nvarchar(max)
  getdate() , -- downloaddate - datetime
  @downloadip -- downloadip - nvarchar(50)
 );");
  execsql(sql.tostring(), null, paras);

  #endregion 添加下载记录

  return response;
  }
  catch
  {
  return new httpresponsemessage(httpstatuscode.nocontent);
  }

  #endregion 下载文件并添加下载记录
 }


8、以上只是我个人的一个小demo,有不对或需要改进的地方还请大家多多提点!

精彩专题分享:asp.net文件上传汇总 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。