
首先明白js是客户带执行代码,c#是服务器上执行代码。本地文件需要用到js处理,服务器端接受c#代码处理
1.HTML页面,文件信息列表用的是datatables.js 不用,那部分可不看:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="LY.CIP.Component.VCS.FileUpload" %>
-
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title></title>
- <script src="media/js/jquery-3.1.1.min.js" type="text/javascript"></script>
- <link href="media/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
- <script src="media/js/jquery.dataTables.min.js" type="text/javascript"></script>
- <script src="FromDataFileupload.js" type="text/javascript"></script>
- <style type="text/css">
- .text-center
- {
- text-align: center;
- }
- .text-left
- {
- text-align: left;
- }
- .text-right
- {
- text-align: right;
- }
- /* dataTables某些标题字体小一号,可以在标题<th><p>测试字体小一号</th>,就可以设置某些列特殊的样式 */
- table.dataTable thead th, table.dataTable thead td
- {
- text-align: center;
- font-weight: normal;
- border-bottom: 0px solid #111;
- }
- body
- {
- font-size: 9pt;
- font-family: 宋体;
- }
- td
- {
- font-size: 9pt;
- font-family: 宋体;
- }
- span
- {
- font-size: 9pt;
- font-family: 宋体;
- }
- button
- {
- font-size: 9pt;
- font-family: 宋体;
- cursor: pointer;
- border-top: #9bc5dd 1px solid;
- height: 22px;
- border-right: #9bc5dd 1px solid;
- background-image: url(/Images/button_bg.jpg);
- background-repeat: repeat-x;
- border-bottom: #9bc5dd 1px solid;
- padding-bottom: 0px;
- padding-top: 2px;
- padding-left: 5px;
- margin: 5px;
- border-left: #9bc5dd 1px solid;
- padding-right: 5px;
- }
- input
- {
- font-size: 9pt;
- font-family: 宋体;
- }
- select
- {
- font-size: 9pt;
- font-family: 宋体;
- }
- </style>
- </head>
- <body>
-
- <div style="width: 96%; margin-left: 2%;">
- <span style="color: #3b516d;">上传区域</span>
- <div style="padding: 0px 0px 0px 5px; width: 100%; border: 1px #b5c7e8 solid">
- <table style="width: 100%">
- <tr>
- <td style="text-align: right; width: 20%;">
- 附件名:
- </td>
- <td style="width: 30%;">
- <input id="fjm" style="width: 100%;" />
- </td>
- <td style="text-align: right; width: 20%;">
- 附件类型:
- </td>
- <td style="width: 30%;">
- <select id="types" style="width: 100%;">
- <% if (optoiondt != null)
- {
- foreach (System.Data.DataRow item in optoiondt.Rows)
- {%>
- <option value="<%=item["lookup_value_code"] %>">
- <%=item["lookup_value_name"]%></option>
- <% }
- }
- %>
- </select>
- </td>
- </tr>
- <tr>
- </tr>
- <tr>
- <td style="text-align: right;">
- 附件上传:
- </td>
- <td style="text-align: left;">
- <input type="file" id="file" style="width: 100%;" />
- </td>
- <td style="text-align: right;">
- 上传状态:
- </td>
- <td style="text-align: left;">
- <span id="output" style="font-size: 12px; margin-left: 10px;">等待</span>
- </td>
- </tr>
- <tr>
- <td colspan="4" style="text-align: right;">
- <button id="upload" style="width: 65px;">
- 上传</button>
- <button id="Button1" style="width: 65px;">
- 暂停</button>
- <button id="Button2" style="width: 65px;">
- 开始</button>
- <button id="Button3" style="width: 65px; ">
- 取消</button>
- </td>
- </tr>
- </table>
- </div>
- <span style="color: #3b516d;">附件区</span>
- <div id="datablesd" style="border: 1px #b5c7e8 solid">
- </div>
- </div>
- </body>
- </html>
2.用js分段文件:
- var isload = 6; //上传状态,初始状态6,上传状态0,暂停状态1,取消状态2
- var loadi = 0; //上传位置
- var succeed = 0; //已上传的位置
- var name = ''; //文件名称
- var shardCount; //文件总片数
- var filenameing = ''; //记录上个上传文件的名称
-
-
- //判断文件是否存在
- var isExistFile = function (url) {
- var relt = false;
- try {
- $.ajax({
- url: "Handler/FileUpload.ashx",
- type: "POST",
- data: { isload: "fly", filename: url },
- async: false, //bu异步
- success: function (result) {
- if (result == "1") relt = true;
- }
- });
- } catch (e) {
-
- }
- return relt;
- };
-
- var page = {
- init: function () {
- var my = this;
- // $("#upload").click($.proxy(my.upload, my));
- $("#upload").on('click', function () {
- if ($("#file")[0].files[0] == undefined) {
- alert("你还未选择上传文件!");
- return;
- }
- //选择文件的文件名
- var filenamete = $("#file")[0].files[0].name;
- //重置文件状态
- if (filenameing != filenamete) {
- isload = 6;
- }
- //截取文件后缀
- var nametype = filenamete.substring(filenamete.lastIndexOf(".") + 1, filenamete.length);
- if ($("#fjm").val() == '' || $("#fjm").val() == undefined) { isload = 6; return alert('请输入文件名再上传!'); }
- name = $("#fjm").val() + '.' + nametype; //文件名
- //判断是否存在文件
- if (isExistFile(name))
- { return alert("该附件已存在请修改附件名!"); }
- //判断文件是否正在上传
- if (isload == 0) {
- return alert("该附件已在上传!");
- }
- //文件最开始上传时候:状态为0,上传进度为0,已上传的位置为0
- isload = 0;
- loadi = 0;
- succeed = 0;
- my.upload();
- })
- //暂停
- $("#Button1").on('click', function () {
- if (isload == 6) {
- return alert("你还未上传文件!");
- }
- isload = 1;
- })
- //开始
- $("#Button2").on('click', function () {
- if ($("#file")[0].files[0] == undefined) {
- alert("你还未选择上传文件!");
- return;
- }
- //选择文件的文件名
- var filenamete = $("#file")[0].files[0].name;
- //截取文件后缀
- var nametype = filenamete.substring(filenamete.lastIndexOf(".") + 1, filenamete.length);
- if ($("#fjm").val() == '' || $("#fjm").val() == undefined) { isload = 6; return alert('请输入文件名再上传!'); }
- name = $("#fjm").val() + '.' + nametype; //文件名
- //判断是否存在文件
- if (isExistFile(name))
- return alert("该附件已存在请修改附件名!");
- //判断文件是否正在上传
- if (isload == 0) {
- return alert("该附件上传未暂停!");
- }
- //文件开始上传时候:状态为0,其他不变
- isload = 0;
- loadi = loadi - 1;
- my.upload();
- })
- //取消
- $("#Button3").on('click', function () {
- if ($("#fjm").val() == '' || $("#fjm").val() == undefined) { isload = 6; return alert('你还未上传!'); }
- if ($("#file")[0].files[0] == undefined) {
- alert("你还未上传!");
- return;
- }
- //文件取消上传时候:状态为2,上传进度为0,已上传的位置为0
- isload = 2;
- setTimeout(function () {
- //Ajax提交
- $.ajax({
- url: "Handler/FileUpload.ashx",
- type: "POST",
- data: { deletes: "all", filename: name, shardCount: shardCount },
- async: true, //异步
- success: function (result) {
- $("#output").text(result);
- }
- });
- //删除之后恢复初始状态
- loadi = 0;
- succeed = 0;
- }, 1000)
- })
- },
-
- upload: function () {
- console.log($("#types").val());
- var file = $("#file")[0].files[0]; //文件对象
- //判断文件的大小
- if (file.size > parseInt($("#filemax").val()) * 1024 * 1024 * 1024) {
- isload = 6; return alert('您上传的文件超过最大限制!');
- }
- //console.log(file.type);
- //选择文件的文件名
- var filenamete = $("#file")[0].files[0].name;
- //赋值当前文件名
- filenameing = filenamete;
- //截取文件后缀
- var nametype = filenamete.substring(filenamete.lastIndexOf(".") + 1, filenamete.length);
- if ($("#fjm").val() == '' || $("#fjm").val() == undefined) { isload = 6; return alert('请输入文件名再上传!'); }
- name = $("#fjm").val() + '.' + nametype; //文件名
- var size = file.size; //总大小
- var shardSize = 2 * 1024 * 1024; //以2MB为一个分片
- shardCount = Math.ceil(size / shardSize); //总片数
- var postsaves = function (i) {
- //计算每一片的起始与结束位置
- var start = i * shardSize,
- end = Math.min(size, start + shardSize);
-
- //构造一个表单,FormData是HTML5新增的
- var form = new FormData();
- form.append("data", file.slice(start, end)); //slice方法用于切出文件的一部分
- form.append("name", name);
- form.append("total", shardCount); //总片数
- form.append("index", i + 1); //当前是第几片
- form.append("serverid", $("#server_order").val());
- form.append("userid", $("#userid").val());
- form.append("types", $("#types").val());
- //判断该块是否存在
- var bolr = isExistFile(name + "_" + (i + 1));
- console.log(bolr + '----' + name + "_" + (i + 1) + "-----" + shardCount);
- //判断是否已经上传过该片
- if (bolr == true) {
- ++succeed;
- //传输未完成
- if (isload == 0 && i < shardCount - 1) {
- //js异步执行该方法
- requestAnimationFrame(function () {
- postsaves(i + 1);
- })
- $("#output").text('验证进度:' + ((succeed / shardCount) * 100).toFixed(0) + " % " + 100);
- }
- } else {
- try {
- //Ajax提交
- $.ajax({
- url: "Handler/FileUpload.ashx",
- type: "POST",
- data: form,
- async: true, //异步
- processData: false, //很重要,告诉jquery不要对form进行处理
- contentType: false, //很重要,指定为false才能形成正确的Content-Type
- success: function (result) {
- if (result == '0' || result == '00') {
- //上传成功时候
- ++succeed;
- }
- if (isload == 0 && i < shardCount - 1) {
- postsaves(i + 1);
- }
- if (isload == 0) {
- $("#output").text('上传进度:' + ((succeed / shardCount) * 100).toFixed(0) + " % " + 100);
- }
- if (result == '00') {
- alert('上传成功!');
- loadtable();
- }
- }, error: function (result) {
- if (confirm('网络连接中断!是否重新连接上传?如果不能重新连接!保证网络时点击继续!')) {
- setTimeout(function () { postsaves(0); }, 2000)
- } else {
- isload = 1;
- }
- } //error end
- }); //ajax end
- } catch (e) {
- }
- } //if else end
- loadi = loadi + 1;
- };
- //执行上传方法入口
- postsaves(loadi);
- }
- };
3.一般处理程序接受分段过来的文件,存放文件的文件夹自建,还有插入数据库步骤方法省略:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.IO;
- using WebApplication1;
-
- namespace LY.CIP.Component.VCS.Handler
- {
- /// <summary>
- /// FileUpload 的摘要说明
- /// </summary>
- public class FileUpload : IHttpHandler
- {
-
- public void ProcessRequest(HttpContext context)
- {
- Rescue rescue = new Rescue();
- context.Response.ContentType = "text/plain";
- try
- {
- if (context.Request.Form["isload"] != null && context.Request.Form["isload"].ToString() == "fly")
- {
- string filename = context.Request.Form["filename"].ToString();
- string dir = context.Server.MapPath("~/FileSave");
- if (File.Exists(dir + "/" + filename))
- context.Response.Write("1");
-
- }
- else
- if (context.Request.Form["deletes"] != null && context.Request.Form["deletes"].ToString() == "all")
- {
- string filename = context.Request.Form["filename"].ToString();
- int shardCount = Convert.ToInt32(context.Request.Form["shardCount"].ToString());
- string dir = context.Server.MapPath("~/FileSave");
- string uurl = dir + "/" + filename;
- for (int i = 1; i < shardCount; i++)
- {
- try
- {
- string uurlnew = uurl + "_" + i;
- if (File.Exists(uurlnew))
- {
- System.IO.File.SetAttributes(uurlnew, System.IO.FileAttributes.Normal);
- File.Delete(uurlnew);
- }
- }
- catch (Exception)
- {
- }
- }
- context.Response.Write("取消成功!");
- }
- else
- {
-
- //从Request中取参数,注意上传的文件在Requst.Files中
- string name = context.Request["name"];
- int total = Convert.ToInt32(context.Request["total"]);
- int index = Convert.ToInt32(context.Request["index"]);
- var data = context.Request.Files["data"];
-
- //保存一个分片到磁盘上
- string dir = context.Server.MapPath("~/FileSave");
- string file = Path.Combine(dir, name + "_" + index);
- data.SaveAs(file);
- context.Response.Write("0");
- //如果已经是最后一个分片,组合
- if (index == total)
- {
- //获取必要参数
- string serverid = context.Request["serverid"];
- string userid = context.Request["userid"];
- string types = context.Request["types"];
-
- file = Path.Combine(dir, name);
- var fs = new FileStream(file, FileMode.Create);
- for (int i = 1; i <= total; ++i)
- {
- string part = Path.Combine(dir, name + "_" + i);
- var bytes = System.IO.File.ReadAllBytes(part);
- fs.Write(bytes, 0, bytes.Length);
- bytes = null;
- System.IO.File.Delete(part);
- }
- fs.Close();
- //截取文件类型
- string filetype = "";
- if (name.LastIndexOf(".") == name.Length - 4)
- {
- filetype = name.Substring(name.LastIndexOf(".") + 1, 3);
- }
- Dictionary<string, object> dic = new Dictionary<string, object>();
- dic.Add("filenmae", name);
- dic.Add("filetype", types);
- dic.Add("filepth", "FileSave/" + name);
- dic.Add("server_id", serverid);
- dic.Add("user_id", userid);
- string reliut =rescue.InsertUploadFileSql(dic);
- if (reliut != "1")
- {
- context.Response.Write("插入数据库失败!");
- }
- else {
- //返回是否成功
- context.Response.Write("0");
- }//if else end
- }// if end
- }// try end
- }
- catch (Exception)
- {
-
- context.Response.Write("1");
- }
- }
-
- public bool IsReusable
- {
- get
- {
- return false;
- }
- }
- }
- }
4.datatables便利文件信息:
- $(function () {
- page.init();
- var datablesd = $("#datablesd");
- var table = '<table id="example" class="display" width="100%" cellspacing="0"> </table>'
- var logr = {
- "sProcessing": "处理中...",
- "sLengthMenu": "显示 _MENU_ 项搜索结果",
- "sZeroRecords": "没有匹配结果",
- "sInfo": "显示第 _START_ 至 _END_ 项结果,共 _TOTAL_ 条附件",
- "sInfoEmpty": "显示第 0 至 0 项结果,共 0 项",
- "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
- "sInfoPostFix": "",
- "sSearch": "搜索:",
- "sUrl": "",
- "sEmptyTable": "暂无文件上传",
- "sLoadingRecords": "载入中...",
- "sInfoThousands": ",",
- "oPaginate": {
- "sFirst": "首页",
- "sPrevious": "上页",
- "sNext": "下页",
- "sLast": "末页"
- }
- };
- var conlius = [
- { "title": "查看", "data": "file_path", "width": "80px", 'sClass': "text-center", render: function (data, type, row) {
- if (row != null) {
- var file_path = row.FILE_PATH;
- return '<a href="' + file_path + '">查看</a>';
- }
- }
- },
- { "title": "删除", "data": "name", "width": "80px", 'sClass': "text-center", render: function (data, type, row) {
- if (row != null) {
- var UPLOAD_FILE_ID = row.UPLOAD_FILE_ID;
- return '<a href="#" class="mydelete" isid="' + UPLOAD_FILE_ID + '">删除</a>';
- }
- }
- },
- { "title": "文件类型", "width": "180px", 'sClass': "text-right", "data": "LOOKUP_VALUE_NAME" },
- { "title": "文件名称", 'sClass': "text-right", "data": "FILE_NAME" }
- ];
- var databless = function (data) {
- datablesd.html('');
- datablesd.append(table);
- $('#example', datablesd).DataTable({
- data: data,
- "serverSide": true,
- searching: true,
- lengthChange: true,
- paging: true,
- scrollCollapse: true,
- serverSide: false,
- search: true,
- processing: true,
- /* scrollY: 500, 表格的高度限制*/
- scrollX: "100%",
- scrollXInner: "100%",
- scrollCollapse: true,
- jQueryUI: false,
- autoWidth: true,
- autoSearch: false,
- pageLength: 10, //每页条数
- bLengthChange: false, //不显示每页显示条数
- searching: false, //搜索
- language: logr,
- oAria: {
- "sSortAscending": ": 以升序排列此列",
- "sSortDescending": ": 以降序排列此列"
- },
- columns: conlius
- });
- $.each($(".mydelete", datablesd), function (i, e) {
- $(e).off("click")
- $(e).on("click", function () {
-
- var id = $(e).attr("isid")
- console.log(id + "--------");
- $.ajax({
- type: "post",
- url: "/FileUpload.aspx/delete",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({ id: id }),
- dataType: "json",
- success: function (d) {
- //0;数据删除失败,1删除成功,2数据删除成功,文件删除失败
- console.log(d);
- if (d.d == "0") {
- alert('删除成功!');
- }
- loadtable();
- },
- error: function (result) {
- // alert(result.responseText);
- }
- }); //ajax end
-
- }); //click end
-
- }); //each end
- }
- loadtable = function () {
- // console.log($("#userid").val());
- // console.log($("#server_order").val());
- var user_id = $("#userid").val();
- var server_id = $("#server_order").val();
-
- $.ajax({
- type: "post",
- url: "/FileUpload.aspx/SayHello",
- contentType: "application/json;charset=utf-8",
- data: JSON.stringify({ user_id: user_id, oerder_id: server_id }),
- dataType: "json",
- success: function (ds) {
- var _res;
- if (ds.d == "") {
- _res = [];
- } else {
- _res = JSON.parse(ds.d);
- }
- //console.log(_res);
- databless(_res);
- },
- error: function (result) {
- //alert(result.responseText);
- }
- });
- }
-
- loadtable();
- });
评价