C#实现多文件上传,写到文件夹中,获取文件信息以及下载文件和删除文件

简介: 前台:.js //上传附件 function uploadAttachment() { if ($("#Tipbind").attr('checked')) { var ip = $("#TunBandIP").

前台:.js

//上传附件
function uploadAttachment() {
    if ($("#Tipbind").attr('checked')) {
        var ip = $("#TunBandIP").val();
        if ($.trim(ip) == 0) {
            return $.messager.show({ title: '提示', msg: '请先选择IP' });
        }
        $('#ImprotDlg').dialog('open');
        uploadFy(ip);
        $("#T_ExcelName").val("");
        $("#T_SheetName").val("");
    }
    else {
        $.messager.show({ title: '提示', msg: '只有绑定的ip才能上传附件' });
    }
}


var oncomplete = false;
function uploadFy(ip) {
    $("#uploadify").uploadify({
        'swf': '/Scripts/uploadify/uploadify.swf',
        'uploader': '/AjaxTerminalInfo/UploadAttachments.cspx',
        'formData': { 'ip': ip },
        'folder': '/Attachments',
        'queueID': 'fileQueue',
        'method': 'get',
        'auto': false,
        'sizeLimit': 20480000,
        'multi': true,
        'fileDesc': '请选择文件',
        'fileExt': '*',
        'width': 110,
        'height': 28,
        'buttonText': '请选择文件',
        'scriptData': {},
        'onSelect': function (e, queueId, fileObj) {
            qId = queueId;

        },
        'onUploadSuccess': function (file, data, response) {
            var datamsg = eval(" val= (" + data + ")");

            if (datamsg.Success) {
                $.messager.show({ title: '提示', msg: datamsg.Success });
                $('#ImprotDlg').dialog('close');
            } else {
                $.messager.show({ title: '提示', msg: datamsg.Error });
            }
            oncomplete = true;
        },
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            if (file.size > 20480000) {
                $.messager.show({ title: '提示', msg: "上传文件不能超过20M" });
            }
        },
        'onCancel': function (file) {

        }
    });
}

//开始上传
function uploadFile() {
    var filename = $("#T_ExcelName").val();
    if (filename == '') {
        $.messager.show({ title: '提示', msg: '请选择上传文件!' });
        return;
    }
    $('#uploadify').uploadify('upload', '*');
}

//取消上传
function cancelUploadFile() {
    $('#uploadify').uploadify('cancel', '*');
    $('#ImprotDlg').dialog('close');
}

//查看附件
function showAttachment() {
    var ip = $("#TunBandIP").val();
    if ($.trim(ip) == 0) {
        return $.messager.show({ title: '提示', msg: '请先选择IP' });
    }
    $("#attachmentDlg").dialog('open');

    var dgObj = {
        queryParams: { ip: ip },
        singleSelect: true,
        url: '/AjaxTerminalInfo/GetAttachmentsByIp.cspx',
        method: 'get',
        border: false,
        toolbar: [{
            text: '下载',
            iconCls: 'icon-import',
            handler: function () {
                var row = $("#dg").datagrid('getChecked');
                if (row.length == 0) {
                    return $.messager.show({ title: '提示', msg: '请先选择文件进行下载' });
                }
                for (var i = 0; i < row.length; i++) {
                    $('#attachmentForm').attr('action', '/AjaxTerminalInfo/DownloadAttachment.cspx?filepath=' + row[i].FilePath + "&filename=" + row[i].FileName);
                    $('#attachmentForm').submit();
                }

            }
        }, {
            text: '删除',
            iconCls: 'icon-no',
            handler: function () {
                alert(1)
            }
        }],
        columns: [[
            { field: 'ck', checkbox: true },
            { field: 'FileName', title: '文件名', width: 310, align: 'left', halign: 'center' },
            { field: 'UploadDateTime', title: '上传日期', width: 120, align: 'center' }
        ]]
    };

    $("#dg").datagrid(dgObj);
}

/// <summary>
/// 删除文件
/// </summary>
/// <param name="filepath"></param>
/// <param name="filename"></param>
/// <returns></returns>
[Action]
[SessionMode(SessionMode.Support)]
public Object DeleteAttachment(string filepath, string filename)
{
Message message = new Message();
try
{
//判断文件是不是存在
if (File.Exists(filepath))
{
//如果存在则删除
File.Delete(filepath);
message.Success = "删除文件成功";
message.data = true;
}
else
{
message.Success = "文件不存在";
message.data = false;
}
return JsonConvert.SerializeObject(message);
}
catch (Exception e)
{
log.Debug("出错原因:" + e.Message);
message.Error = "删除文件失败:" + e.Message;
message.data = false;
return JsonConvert.SerializeObject(message);
}
}

 

后台:.cs

/// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
        [Action]
        [SessionMode(SessionMode.Support)]
        public object UploadAttachments()
        {
            var message = new Message();
            try
            {
                HttpPostedFile file = HttpContext.Current.Request.Files["Filedata"];
                var ip = HttpContext.Current.Request.Params["ip"];
                string path = "/Attachments/" + ip + "/";//相对路径


                if (file != null && file.ContentLength > 0)
                {
                    string savePath = Path.Combine(HttpContext.Current.Server.MapPath(path));
                    if (!Directory.Exists(savePath))
                        Directory.CreateDirectory(savePath);
                    file.SaveAs(savePath + file.FileName);
                    message.Success = "上传成功";
                }
                else
                {
                    message.Error = "文件不能为空";
                }
            }
            catch (Exception e)
            {
                log.Debug("出错原因:" + e.Message);
                message.Error = "出错原因:" + e.Message;
                throw;
            }
            return JsonConvert.SerializeObject(message);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Action]
        [SessionMode(SessionMode.Support)]
        public object GetAttachmentsByIp(string ip)
        {
            try
            {
                string path = "/Attachments/" + ip + "/";//相对路径
                string savePath = Path.Combine(HttpContext.Current.Server.MapPath(path));
                var dgData = new DataGridData<DiyFile>();
                string[] fileNames = Directory.GetFiles(savePath);
                foreach (var fileName in fileNames)
                {
                    var fi = new FileInfo(fileName);
                    var fileinfo = new DiyFile();
                    fileinfo.FileName = fi.Name;
                    fileinfo.FilePath = fileName;
                    fileinfo.UploadDateTime = fi.LastAccessTime;
                    dgData.rows.Add(fileinfo);
                }
                dgData.total = fileNames.Count();
                var dgJson = JsonConvert.SerializeObject(dgData);
                return dgJson;
            }
            catch (Exception e)
            {
                log.Debug("出错原因:" + e.Message);
                throw;
            }
        }

        [Action]
        [SessionMode(SessionMode.Support)]
        public void DownloadAttachment(string filepath,string filename)
        {
            try
            {
                using (var fs = new FileStream(filepath, FileMode.OpenOrCreate))
                {
                    var bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode(filename, Encoding.UTF8));
                    HttpContext.Current.Response.BinaryWrite(bytes);
                    HttpContext.Current.Response.Flush();
                    fs.Close();
                }
            }
            catch (Exception e)
            {
                log.Debug("出错原因:" + e.Message);
                throw;
            }
        }

 

目录
相关文章
|
数据采集 JavaScript C#
C#图像爬虫实战:从Walmart网站下载图片
C#图像爬虫实战:从Walmart网站下载图片
|
12月前
|
存储 监控 算法
基于 C# 的局域网计算机监控系统文件变更实时监测算法设计与实现研究
本文介绍了一种基于C#语言的局域网文件变更监控算法,通过事件驱动与批处理机制结合,实现高效、低负载的文件系统实时监控。核心内容涵盖监控机制选择(如事件触发机制)、数据结构设计(如监控文件列表、事件队列)及批处理优化策略。文章详细解析了C#实现的核心代码,并提出性能优化与可靠性保障措施,包括批量处理、事件过滤和异步处理等技术。最后,探讨了该算法在企业数据安全监控、文件同步备份等场景的应用潜力,以及未来向智能化扩展的方向,如文件内容分析、智能告警机制和分布式监控架构。
298 3
|
数据采集 XML JavaScript
C# 中 ScrapySharp 的多线程下载策略
C# 中 ScrapySharp 的多线程下载策略
c# 创建文件夹
在 C# 中,创建文件夹和文件依赖于 .NET 框架提供的 `System.IO` 命名空间中的类与操作系统交互。
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
基于 C# 编写的 Visual Studio 文件编码显示与修改扩展插件
519 9
|
监控 前端开发 安全
C#一分钟浅谈:文件上传与下载功能实现
【10月更文挑战第2天】在Web应用开发中,文件的上传与下载是常见需求。本文从基础入手,详细讲解如何在C#环境下实现文件上传与下载。首先介绍前端表单设计及后端接收保存方法,使用`&lt;input type=&quot;file&quot;&gt;`与`IFormFile`接口;接着探讨错误处理与优化策略,如安全性验证和路径管理;最后讲解文件下载的基本步骤,包括确定文件位置、设置响应头及发送文件流。此外,还提供了进阶技巧,如并发处理、大文件分块上传及进度监控,帮助开发者构建更健壮的应用系统。
1026 16
|
C# Windows
C#实现指南:将文件夹与exe合并为一个exe
C#实现指南:将文件夹与exe合并为一个exe
1415 9
|
存储 C#
【C#】大批量判断文件是否存在的两种方法效率对比
【C#】大批量判断文件是否存在的两种方法效率对比
550 1
|
安全 C# 数据安全/隐私保护
实现C#编程文件夹加锁保护
【10月更文挑战第16天】本文介绍了两种用 C# 实现文件夹保护的方法:一是通过设置文件系统权限,阻止普通用户访问;二是使用加密技术,对文件夹中的文件进行加密,防止未授权访问。提供了示例代码和使用方法,适用于不同安全需求的场景。
756 0
|
XML 存储 缓存
C#使用XML文件的详解及示例
C#使用XML文件的详解及示例
884 0