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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#实现多文件上传,写到文件夹中,获取文件信息以及下载文件和删除文件相关的知识,希望对你有一定的参考价值。

前台:.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;
            }
        }

 

以上是关于C#实现多文件上传,写到文件夹中,获取文件信息以及下载文件和删除文件的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot项目优雅的实现多配置文件切换以及获取配置信息

SpringBoot项目优雅的实现多配置文件切换以及获取配置信息

SpringBoot项目优雅的实现多配置文件切换以及获取配置信息

C# Winform 多线程 SOCKET 文件上传,下载

多文件上传以及java后台接受

多文件上传以及java后台接受