C#實現多檔案上傳,寫到檔案夾中,擷取檔案資訊以及下載檔案和刪除檔案

來源:互聯網
上載者:User

標籤:

前台:.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#實現多檔案上傳,寫到檔案夾中,擷取檔案資訊以及下載檔案和刪除檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.