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 > )
{
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#实现多文件上传,写到文件夹中,获取文件信息以及下载文件和删除文件的更多相关文章
- C&C控制服务的设计和侦测方法综述——DDoS攻击,上传从宿主机偷窃的到的信息,定时给感染机文件加密勒索等。
这篇文章总结了一些我在安全工作里见到过的千奇百怪的C&C控制服务器的设计方法以及对应的侦测方法,在每个C&C控制服务先介绍黑帽部分即针对不同目的的C&C服务器设计方法,再介绍白 ...
- 文件上传插件Uploadify在Struts2中的应用,完整详细实例
—>最近由于项目需要使用到一个上传插件,在网上发现uploadify挺不错,所以决定使用它,但是官网文档和例子是php的,而项目是SSI框架的,所以自己对uploadify在struts2中的使 ...
- Node开发文件上传系统及向七牛云存储和亚马逊AWS S3的文件上传
背景起,有奏乐: 有伟人曰:学习技能的最好途径莫过于理论与实践相结合. 初学Node这货时,每每读教程必会Fall asleep. 当真要开发系统时,顿觉精神百倍,即便踩坑无数也不失斗志. 因为同团队 ...
- JQuery文件上传插件uploadify在MVC中Session丢失的解决方案
<script type="text/javascript"> var auth = "@(Request.Cookies[FormsAuthenticati ...
- 在Express中使用Multiparty进行文件上传及POST、GET参数获取
Express 版本:4.14.1 在Express中,文件上传需要用到multiparty中间件,在项目目录中,通过npm install multiparty –save进行安装必要组件. 前端H ...
- .net core webapi 文件上传在 Swagger 文档中的有好提示处理
前提: 需要nuget Swashbuckle.AspNetCore 我暂时用的是 4.01 最新版本: 描述:解决 .net core webapi 上传文件使用的是 IFormFile,在S ...
- ASP.NET CORE RAZOR :将文件上传至 ASP.NET Core 中的 Razor 页面
本部分演示使用 Razor 页面上传文件. 本教程中的 Razor 页面 Movie 示例应用使用简单的模型绑定上传文件,非常适合上传小型文件. 有关流式传输大文件的信息,请参阅通过流式传输上传大文件 ...
- multipart/form-data 文件上传表单中 传递参数无法获取的原因!
1.什么是multipart/form-data 首先我们需要明白在html中的enctype属性, enctype:规定了form表单在发送到服务器时候编码方式.他有如下的三个值. ①applica ...
- 文件上传时jquery.form.js中提示form.submit SCRIPT5: 拒绝访问
利用其它控件触发file的click事件来选择文件后,使用jquery.form.js中的submit方法提交时IE报错:form.submit SCRIPT5: 拒绝访问,其它浏览器正常, < ...
- SpringBoot文件上传大小设置(yml中配置)
#文件大小 MB必须大写 # maxFileSize 是单个文件大小 # maxRequestSize是设置总上传的数据大小 spring: servlet: multipart: enabled: ...
随机推荐
- Java去掉Html标签的方法
content = content.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("< ...
- 老猪带你玩转android自定义控件二——自定义索引栏listview
带索引栏的listview,在android开发非常普遍,方便用户进行字母索引,就像微信通讯录这样: 今天,我们就从零到一实现这个具有索引栏的listview. 怎么实现这个控件了,我们应当梳理出一个 ...
- 【R】函数-统计函数
- MySQL数据库localhost的root用户登陆遭遇失败
问题:Access denied for user 'root'@'localhost' (using password: YES)打开MySQL目录下的my.ini文件(Linux的话是/etc/m ...
- OpenGL book list
From: https://www.codeproject.com/Articles/771225/Learning-Modern-OpenGL A little guide about mo ...
- [Git] Undo my last commit and split it into two separate ones
When you accidentally committed some changes to your branch you have various possibilities to “undo” ...
- WIN10系统如何隐藏底部搜索框
右击任务栏,搜索,可以切换三种模式,建议还是显示搜索图标,因为这个搜索还是能比较快速定位到系统功能的,只不过显示搜索框的话比较占地方,不方便
- js检测来源网址,如果是搜索引擎跳转到新地址
[js]代码 <script> var regexp=/\.(sogou|soso|baidu|google|youdao|yahoo|bing|118114|biso|gougou|if ...
- Invalid volume failure config value: 1
原因: hdfs-site.xml中的配置为: <property> <name>dfs.datanode.failed.volumes.tolerated</name& ...
- google protocol buffer 简介 版本 安装 使用 实例
一.简介 protocolbuffer(以下简称PB)是google 的一种数据交换的格式,它独立于语言,独立于平台.google 提供了三种语言的实现:java.c++ 和 python,每一种实现 ...