ASP.NET 文件上传的实现(Upload)

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">&nbsp;</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 [email protected]");
                    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 [email protected];
");
                    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 [email protected] ");

            #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,有不对或需要改进的地方还请大家多多提点!

时间: 2024-12-24 05:08:06

ASP.NET 文件上传的实现(Upload)的相关文章

ASP中文件上传组件ASPUpload介绍和使用方法

[导读]要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件 1 下载和安装ASPUpload  要实现该功能,就要利用一些特制的文件上传组件.文件上传组件网页非常多,这里介绍国际上非常有名的ASPUpload组件,它的下载网址是:           http://www.persits.com/aspupload.exe       组件提供者网址是:           http://www.aspupload.com    

你以为的ASP.NET文件上传大小限制是你以为的吗

我们以为的文件大小限制 我们大家都知道ASP.NET为我们提供了文件上传服务器控件FileUpload,默认情况下可上传的最大文件为4M,如果要改变可上传文件大小限制,那么我们可以在web.config中的httpRuntime元素中添加maxRequestLength属性设置大小,同时为了支持大文件上传超时可以添加executionTimeout属性设置超时时间.网上有很多这样的例子,但实际情况是否是这样吗? <httpRuntime maxRequestLength="" e

asp.net 文件上传出错:Maximum request length exceeded 解决方法

<configuration>    <system.web>               <httpRuntime maxRequestLength="102400" useFullyQualifiedRedirectUrl="true" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="10

jQuery文件上传插件jQuery Upload File 有上传进度条

jQuery文件上传插件jQuery Upload File 有上传进度条 2015年05月15日 jQuery文件上传插件jQuery Upload File,插件使用简单,支持单文件和多文件上传,支持文件拖拽上传,有进度条显示.标准HTML form文件上传,也就是说,只要服务端支持接收multipart/form-data格式数据就能使用此上传插件. 本站web端文件文件提交即使用此插件,效果如下: 浏览器支持 浏览器支持:IE 8.0,IE 9.0,IE 10.0,Firefox,Saf

2014.12.13 ASP.NET文件上传

一.文件上传:(一)上传到硬盘文件夹1.最简单的上传. [HTML代码] 1 <asp:FileUpload ID="FileUpload1" runat="server" /> 2 <asp:Button ID="Button1" runat="server" Text="上传" /> [C#代码] 1 //把相对路径,变成绝对路径 2 string path = Server.M

ASP.NET文件上传大小的限制解决方案

我们大家都知道ASP.NET为我们提供了文件上传服务器控件FileUpload,默认情况下可上传的最大文件为4M,如果要改变可上传文件大小限制,那么我们可以在web.config中的httpRuntime元素中添加maxRequestLength属性设置大小,同时为了支持大文件上传超时可以添加executionTimeout属性设置超时时间.网上有很多这样的例子,但实际情况是否是这样吗? <httpRuntime maxRequestLength="" executionTime

ASP.NET文件上传大小限制

上传限制 我们以为的文件大小限制 我们大家都知道ASP.NET为我们提供了文件上传服务器控件FileUpload,默认情况下可上传的最大文件为4M,如果要改变可上传文件大小限制,那么我们可以在web.config中的httpRuntime元素中添加maxRequestLength属性设置大小,同时为了支持大文件上传超时可以添加executionTimeout属性设置超时时间.网上有很多这样的例子,但实际情况是否是这样吗? <httpRuntime maxRequestLength="&qu

ASP.NET 文件上传类 简单好用

调用: UploadFile uf = new UploadFile(); //参数设置 //uf.SetFilePath="" 设置保存路径,默认为upload //uf.SetFileType=".exe" 设置允许的后缀格式,默认为.pdf,.xls,.xlsx,.doc,.docx,.txt //uf.SetMaxSizeM=100 设置最大上传大小 默认10M //执行保存 uf.Save("file" /*input file 的 n

DVWA 黑客攻防实战(五)文件上传漏洞 File Upload

说起文件上传漏洞 ,可谓是印象深刻.有次公司的网站突然访问不到了,同事去服务器看了一下.所有 webroot 文件夹下的所有文件都被重命名成其他文件,比如 jsp 文件变成 jsp.s ,以致于路径映射不到 jsp 文件,同事怀疑是攻击者上传了个 webshell 文件然后进行批量重命名了. 把后台的代码都找了一遍,后台代码也都有验证文件扩展名的,后面是发现一张普通的照片其实是代码来的,但也不知道为何能够执行.但看完这篇文章你就会明白了. 下面用 dvwa 来演示如何攻击和防御. 低级 用户界面