文件上传服务器,删除下载操作

文件上传控制器

  private readonly string UPLOAD_DIRECTORY = "UploadFile/";
        /// <summary>
        /// 文件上传逻辑
        /// </summary>
        [HttpPost]
        public JsonResult UpLoadFileSubmit()
        {
            List<FileUploadRecord> records = new List<FileUploadRecord>();
            //上传的路径
            string filepath = Server.MapPath("~/" + UPLOAD_DIRECTORY);
            //request获取的文件对象
            var files = HttpContext.Request.Files;
            try
            {
                //超时返回首页
              /*  if (Session["UserId"].Equals(string.Empty))
                {
                    HttpContext.Response.RedirectToRoute(new { Controller = "Timer", Action = "Timer" });
                }*/
                for (int i = 0; i < files.Count; i++)
                {
                    //查看mime type类型
                    //string mimetype = files[i].ContentType;
                    string fileName = files[i].FileName;
                    //针对小文件可以使用此方法
                    //判断目录存在不存在,不存在创建
                    if (!Directory.Exists(filepath)) Directory.CreateDirectory(filepath);
                    files[i].SaveAs(filepath + fileName);
                    //更改文件名称
                    //获取文件后缀名
                    string suffix = Path.GetExtension(filepath + fileName);
                    string uuid = System.Guid.NewGuid().ToString("N");
                    string realName = uuid + suffix;
                    //更改文件名
                    FileInfo fileInfo = new FileInfo(filepath + fileName);
                    fileInfo.MoveTo(filepath + realName);

                    records.Add(new FileUploadRecord() {
                        Id = realName,
                        FileName = fileName,
                        UserId = Convert.ToInt32(Session["UserId"]),//暂时写死
                        UpLoadTime = DateTime.Now,
                        Status = 0,
                    });

                }
                //状态记录在数据库里
                /*BaseDBContext db = new BaseDBContext();
                db.FileUploadRecords.AddRange(records);
                //记录日志
                string template = SystemLogTemplate.UpLoadFile;
                StringBuilder filenames = new StringBuilder();
                records.ForEach(c => {
                    filenames.Append(c.FileName);
                    filenames.Append(";");
                });
                template = template.Replace("{filenames}", filenames.ToString());
                template = template.Replace("{num}", records.Count.ToString());


                db.SystemLogs.Add(new SystemLog()
                {
                    UserName = Session["UserName"].ToString(),
                    CreateTime = DateTime.Now,
                    Operaction = template
                }); 
*/
                db.SaveChanges();
                db.Dispose();
            }
            catch (Exception)
            {
                return Json(new { type = 0, msg = "失败!" });
            }

            return Json(new { type = 1, msg = "成功!" });
        }
         /// <summary>
        /// 删除
        /// </summary>
        /// <param name="uuid"></param>
        public void DeleteUpLoadFile(string uuid)
        {
            using (BaseDBContext db = new BaseDBContext())
            {
                //删除数据库文件
                FileUploadRecord find = db.FileUploadRecords.Find(uuid);
                find.Status = 1;//服务器文件删除后状态
                db.FileUploadRecords.Attach(find);
                db.Entry<FileUploadRecord>(find).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            //删除上传到服务器的文件
            string filepath = Server.MapPath("~/" + UPLOAD_DIRECTORY);
            FileInfo deleteinfo = new FileInfo(filepath + uuid);
            if (deleteinfo.Exists) deleteinfo.Delete();
        }
 /// <summary>
        /// 下载文件  查看内容
        /// </summary>
        /// <param name="n_name"></param>
        [HttpGet]
        public void DownLoad(string n_name)
        {
            //获取下载文件名称
            string Down = null;
            try
            {
                using (BaseDBContext db = new BaseDBContext())
                {
                    Down = db.FileUploadRecords.Where(u => u.Id == n_name).FirstOrDefault().FileName;
                }
            }
            catch (Exception)
            {

            }
            if (!string.IsNullOrEmpty(n_name))
            {
                HttpResponse response = System.Web.HttpContext.Current.Response;
                //获取服务器地址
                string path = System.Web.HttpContext.Current.Server.MapPath(@"~\\UploadFile\\" + n_name);
                FileInfo fi = new FileInfo(path);
                if (fi.Exists)
                {
                    //attachment 下载
                    //inline查看
                    response.Clear();

                    response.AddHeader("Content-Disposition", "inline; filename=" + System.Web.HttpContext.Current.Server.UrlEncode(Down));
                    response.AddHeader("Content-Length", fi.Length.ToString());
                    response.ContentType = "application/octet-stream";
                    // response.ContentType = "application/vnd.ms-excel";

                    //  response.TransmitFile(fi.FullName);
                    response.Filter.Close();
                    response.WriteFile(fi.FullName);
                    response.End();
                }
                else
                {
                    response.Status = "404 File Not Found";
                    response.StatusCode = 404;
                    response.StatusDescription = "File Not Found";
                    response.Write("File Not Found");
                    response.End();
                }
            }
        }

前端

@model List<iLab.Dao.Entity.FileUploadRecord>
<script src="~/Scripts/jquery-3.3.1.js"></script>
<script src="~/Scripts/jquery.dataTables.min.js"></script>

<h2>用户名: @ViewBag.UserName</h2>
<div class="container">
    <div class="row">
        <div class="col-md-12 ">
            <br><br>
            <!-- 表单区域-->
                <fieldset enctype="multipart/form-data">
                    <!--表单主题-->
                    <legend>文件上传</legend>
                    <!-- 每一个form-group都可以自定义布局-->
                    <div class="form-group">
                        <!-- label表示文字提示标签,可以通过表单的组建的id提示-->
                        <label class="col-md-2 control-label" for="mid">选择文件</label>
                        <div class="col-md-4">
                            <input class="form-control" id="files" type="file" name="file" multiple />
                        </div>
                        <input class="btn btn-primary" id="uploadFile" type="button" value="上传" style="float:left" />                      
                        &nbsp;&nbsp;
                        <input class="btn btn-primary" id="uploadDatabase" type="button" value="批量传送数据库" />
                    </div>
                    

                </fieldset>
        </div>
    </div>
</div>

<table id="data_table" class="table table-border table-bordered table-bg table-responsive" style="width:100%">
    <caption>结果集</caption>
    <thead>
        <tr class="text-c">
            <th width="5"><input type="checkbox" id="check_all" class="check_all"></th>
            @*<th>UUID</th>*@
            <th>文件名称</th>
            @*<th>状态</th>*@
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr class="text-c">
                <td align="center"><input type="checkbox" name="CheckBoxName" class="dxk" value="@item.Id"></td>
                @*<td>@item.Id</td>*@
                <td>@item.FileName</td>
                @*<td>@item.Status</td>*@
                <td>
                    @if (ViewBag.RoleId > 0)
                    {
                        <a onclick="deleteItem('@item.Id')">删除</a>
                    }
                    <a id="upload" href="@Url.Content("~/ICPMS/DownLoad?n_name="+@item.Id)" target="_blank">查看</a>
                    <a href="~/ICPMS/WriteIntoDataBase?uuid=@item.Id">写入数据库</a>
                    
                    @*&nbsp;<a onclick="ViewFile('@item.Id')">查看</a>
        &nbsp;<a onclick="ModifyFile('@item.Id')">修改</a>*@
                </td>
            </tr>
        }
    </tbody>
    
     
</table>

<script>
       //按钮全选和反选
    $('#data_table').DataTable({
        searching: false,
        destroy: true,
        autoWidth: true,
        ordering: false,
    });

    $('#check_all').click(function() {
        if (this.checked) {
            $("input[name='CheckBoxName']").each(function () {
                this.checked = true;
            });
        }
        else {
            $("input[name='CheckBoxName']").each(function () {
                this.checked = false;
            });
        }
    });

    //批量上传数据库
    $('#uploadDatabase').click(function () {
        var ids = new Array();
        $("input[name='CheckBoxName']").each(function () {
            if (this.checked) {
                ids.push($(this).val());
            }
        });
        console.log(ids);
        if (ids.length == 0) {
            alert('请至少选择一条数据!');
            return;
        }

        $.ajax({
            url: '/ICPMS/UploadDatabase',
            type: 'post',
            data: { ids: ids },
            success: function () {

                window.location.reload();
            },
            error: function () {

            }
        });

    });
    
    //删除
    function deleteItem(uuid) {
        if (confirm('确定要删除这条数据嘛?')) {
            $.ajax({
                url: '/ICPMS/DeleteUpLoadFile',
                type: 'post',
                data: { uuid: uuid },
                success: function () {
                    alert('删除成功!');
                    window.location.reload();
                },
                error: function () {
                    alert('未知错误!');
                }
            });
        }
    }
    //查看
    function ViewFile(uuid) {

        alert(uuid);

        $.ajax({
            url: '/ICPMS/ViewFile',
            dataType: 'json',
            type:'post',
            data: { uuid: uuid },
            success: function (msg) {
                alert(msg.msg);
                alert(msg);
                //Response.TransmitFile(msg.msg);
         $.download(msg, 'post', msg.filePath, msg.fileName); // 下载文件 
              
            },
            error: function () {
                 alert('未知错误!');
            }


        })

    }
    //修改
    function ModifyFile(uuid) {
        if (confirm('确定要修改这条数据吗')) {
          
            $.ajax({
                url: '/ICPMS/ModifyFile',
                type: 'post',
                data: { uuid: uuid },
                success: function () {
                   alert("修改完成");
                   window.reload();
                    
                },
                error: function () {
                    alert('未知错误');
                }
            })
        }
    }

    //文件上传服务器
    $(document).ready(function () {
        $('#uploadFile').click(function () {
            //判断是否有文件
            var count = $('#files')[0].files.length;
            if (count == 0) {
                alert('您未选择任何文件!');
                return;
            } else {
                var fileUpload = $("#files").get(0);
                var files = fileUpload.files;
                var data = new FormData();
                for (var i = 0; i < files.length; i++) {
                    data.append(files[i].name, files[i]);
                }

                $.ajax({
                    url: '/ICPMS/UpLoadFileSubmit',
                    dataType: 'json',
                    type: 'post',
                    async: false,
                    data: data,
                    processData: false,
                    contentType: false,
                    success: function (response) {
                        alert('上传成功!');
                        $('#myFileAjax').val('');
                        //刷新页面
                        window.location.reload();
                    }, error: function (msg) {
                        alert('未知错误!');
                    }
                });
            }
        });
    });
</script>

实体类

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace iLab.Dao.Entity
{
    [Table("FileUploadRecord")]
    public class FileUploadRecord
    {
        [Key]
        public string Id { get; set; }

        public string FileName { get; set; }

        public int? UserId { get; set; }

        public int? Status { get; set; }
        
        public DateTime? UpLoadTime { get; set; }
        public DateTime? Modify { get; set; }

        public string ModifyUser { get; set; }

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值