前台:.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 > )
{
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, , 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#实现多文件上传,写到文件夹中,获取文件信息以及下载文件和删除文件的更多相关文章

  1. C&C控制服务的设计和侦测方法综述——DDoS攻击,上传从宿主机偷窃的到的信息,定时给感染机文件加密勒索等。

    这篇文章总结了一些我在安全工作里见到过的千奇百怪的C&C控制服务器的设计方法以及对应的侦测方法,在每个C&C控制服务先介绍黑帽部分即针对不同目的的C&C服务器设计方法,再介绍白 ...

  2. 文件上传插件Uploadify在Struts2中的应用,完整详细实例

    —>最近由于项目需要使用到一个上传插件,在网上发现uploadify挺不错,所以决定使用它,但是官网文档和例子是php的,而项目是SSI框架的,所以自己对uploadify在struts2中的使 ...

  3. Node开发文件上传系统及向七牛云存储和亚马逊AWS S3的文件上传

    背景起,有奏乐: 有伟人曰:学习技能的最好途径莫过于理论与实践相结合. 初学Node这货时,每每读教程必会Fall asleep. 当真要开发系统时,顿觉精神百倍,即便踩坑无数也不失斗志. 因为同团队 ...

  4. JQuery文件上传插件uploadify在MVC中Session丢失的解决方案

    <script type="text/javascript"> var auth = "@(Request.Cookies[FormsAuthenticati ...

  5. 在Express中使用Multiparty进行文件上传及POST、GET参数获取

    Express 版本:4.14.1 在Express中,文件上传需要用到multiparty中间件,在项目目录中,通过npm install multiparty –save进行安装必要组件. 前端H ...

  6. .net core webapi 文件上传在 Swagger 文档中的有好提示处理

    前提: 需要nuget   Swashbuckle.AspNetCore 我暂时用的是  4.01 最新版本: 描述:解决 .net core webapi 上传文件使用的是 IFormFile,在S ...

  7. ASP.NET CORE RAZOR :将文件上传至 ASP.NET Core 中的 Razor 页面

    本部分演示使用 Razor 页面上传文件. 本教程中的 Razor 页面 Movie 示例应用使用简单的模型绑定上传文件,非常适合上传小型文件. 有关流式传输大文件的信息,请参阅通过流式传输上传大文件 ...

  8. multipart/form-data 文件上传表单中 传递参数无法获取的原因!

    1.什么是multipart/form-data 首先我们需要明白在html中的enctype属性, enctype:规定了form表单在发送到服务器时候编码方式.他有如下的三个值. ①applica ...

  9. 文件上传时jquery.form.js中提示form.submit SCRIPT5: 拒绝访问

    利用其它控件触发file的click事件来选择文件后,使用jquery.form.js中的submit方法提交时IE报错:form.submit SCRIPT5: 拒绝访问,其它浏览器正常, < ...

  10. SpringBoot文件上传大小设置(yml中配置)

    #文件大小 MB必须大写 # maxFileSize 是单个文件大小 # maxRequestSize是设置总上传的数据大小 spring: servlet: multipart: enabled: ...

随机推荐

  1. RV32FD指令集

    Risc-V架构定义了可选的单精度浮点指令(F扩展指令集)和双精度浮点指令(D扩展指令集). Risc-V架构规定:处理器可以选择只实现F扩展指令子集而不支持D扩展指令子集:但是如果支持了D扩展指令子 ...

  2. 在linux机器上面安装anaconda和相关软件

    直接安装anaconda参考这里,主要两条命令: wget https://repo.continuum.io/archive/Anaconda3-5.0.1-Linux-x86_64.sh bash ...

  3. 用 Vue 改造 Bootstrap,渐进提升项目框架[转]

    GitChat 作者:Meathill 原文:用 Vue 改造 Bootstrap,渐进提升项目框架 关注微信公众号:「GitChat 技术杂谈」 一本正经的讲技术 [不要错过文末彩蛋] 前言 Vue ...

  4. [leetcode]Gray Code @ Python

    原题地址:https://oj.leetcode.com/problems/gray-code/ 题意: The gray code is a binary numeral system where ...

  5. [PowerShell Utils] Automatically Change DNS and then Join Domain

    I would like to start a series of blog posts sharing PowerShell scripts to speed up our solution ope ...

  6. js遍历jstl数组

    查询到在js中可以使用jstl <script> <c:forEach items="${channel.templates}" var="templa ...

  7. PostgreSQL入门教程

    一.安装 首先,安装PostgreSQL客户端. sudo apt-get install postgresql-client 然后,安装PostgreSQL服务器. sudo apt-get ins ...

  8. javascript中IE浏览器不支持NEW DATE()带参数的解决方法

    代码如下: var date1=new Date(dateTimes[z][1]); 在火狐下 可以正常取得时间,在IE7下 却是 NaN.纠结老长时间,放弃了new date 然后再老外的论坛中找了 ...

  9. JavaScript 时间、格式、转换及Date对象总结

    悲剧的遇到问题,从前台得到时间,“Tue Jan 29 16:13:11 UTC+0800 2008”这种格式的,想再后台解析成想要的格式,但是在后台就是解析不了SimpleDateFormat也试着 ...

  10. ASP.NET 打包多CSS或JS文件以加快页面加载速度的Handler

    ASP.NET 打包多CSS或JS文件以加快页面加载速度的Handler, 使用<link type="text/css" rel="Stylesheet" ...