文件的导入

Posted IWantPower

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件的导入相关的知识,希望对你有一定的参考价值。

首先要引入一个JS包:  <script src="/Themes/Default/Scripts/ajaxupload.js"></script>

//  前台html

<!-- 上传文件入库-->
        <div class="uploadFile">
            <span id="doc">
                <input type="text" disabled="disabled" /></span>
            <input type="hidden" id="hidFileName" />
            <input type="button" id="btnUploadFile" value="上传" />
            <input type="button" id="btnDeleteFile" value="删除" />
        </div>  

//  前台函数

   //初始化文档上传
        function init() {
            //初始化文档上传  
            var btnFile = document.getElementById("btnUploadFile");
            var doc = document.getElementById("doc");
            var hidFileName = document.getElementById("hidFileName");
            document.getElementById("btnDeleteFile").onclick = function () { DelFile(doc, hidFileName); };
            g_AjxUploadFile(btnFile, doc, hidFileName);
        }
        var g_AjxTempDir = "/Upload/txt/";  // 上传文件所要保存的文件夹
        //文档上传  
        function g_AjxUploadFile(btn, doc, hidPut, action) {
            var button = btn, interval;
            new AjaxUpload(button, {
                action: ((action == null || action == undefined) ? ‘/Ajax/GetFiletxt.ashx?fileType=file‘ : action),
                data: {},
                name: ‘myfile‘,
                onSubmit: function (file, ext) {

                //判断文件上传的格式

                  // if (!(ext && /^(rar|zip|pdf|pdfx|txt|csv|xls|xlsx|doc|docx|RAR|ZIP|PDF|PDFX|TXT|CSV|XLS|XLSX|DOC|DOCX)$/.test(ext))) {
                    if (!(ext && /^(txt|TXT)$/.test(ext))) {
                        alert("您上传的文档格式不对,请重新选择!");
                        return false;
                    }
                },
                onComplete: function (file, response) {
                    flagValue = response;
                    if (flagValue == "1") {
                        alert("您上传的文档格式不对,请重新选择!");
                    }
                    else if (flagValue == "2") {
                        alert("您上传的文档大于2M,请重新选择!");
                    }
                    else if (flagValue == "3") {
                        alert("文档上传失败!");
                    }
                    else {
                        hidPut.value = response;
                        //doc.innerHTML = "<a href=‘" + g_AjxTempDir + response + "‘ target=‘_blank‘>" + response + "</a>";
                        doc.innerHTML = response;
                    }
                }
            });
        }

        function DelFile(doc, hidPut) {
            hidPut.value = "";
            doc.innerHTML = "<input type=\"text\" disabled=\"disabled\" />";
        }

 

//  ajax  后台

         private string _filedir = "";    //文件目录  
        /// <summary>  
        /// 处理上传文件(1:文件格式不正确、2:文件大小不正确、3:上传失败、文件名称:上传成功)  
        /// </summary>  
        /// <param name="context"></param>  
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            _filedir = context.Server.MapPath(@"/Upload/txt/");
            try
            {
                string result = "3";
                string fileType = context.Request.QueryString["fileType"]; //获取上传文件类型  
                if (fileType == "file")
                {
                    result = UploadFile(context);  //文档上传  
                }
                context.Response.Write(result);
            }
            catch
            {
                context.Response.Write("文件上传失败");//3文件上传失败  
            }
        }
        /// <summary>  
        /// 文档上传  
        /// </summary>  
        /// <param name="context"></param>  
        /// <returns></returns>  
        private string UploadFile(HttpContext context)
        {
            BKS_EquipMentParameter BKE = new BKS_EquipMentParameter();
            int cout = context.Request.Files.Count;
            if (cout > 0)
            {
                HttpPostedFile hpf = context.Request.Files[0];
                if (hpf != null)
                {
                    string fileExt = Path.GetExtension(hpf.FileName).ToLower();
                    //只能上传文件,过滤不可上传的文件类型    

                    //string fileFilt = ".rar|.zip|.pdf|.pdfx|.txt|.csv|.xls|.xlsx|.doc|.docx......";
                    string fileFilt = ".txt ";
                    if (fileFilt.IndexOf(fileExt) <= -1)
                    {
                        return "1";
                    }

                    //判断文件大小    
                    int length = hpf.ContentLength;
                    if (length > 2097152)
                    {
                        return "2";
                    }

                    Random rd = new Random();
                    DateTime nowTime = DateTime.Now;
                    string newFileName = nowTime.Year.ToString() + nowTime.Month.ToString() + nowTime.Day.ToString() + nowTime.Hour.ToString() + nowTime.Minute.ToString() + nowTime.Second.ToString() + rd.Next(1000, 1000000) + Path.GetExtension(hpf.FileName);
                    if (!Directory.Exists(_filedir))
                    {
                        Directory.CreateDirectory(_filedir);
                    }
                    string fileName = _filedir + newFileName;
                    hpf.SaveAs(fileName);


                    FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.None);
                    StreamReader sr = new StreamReader(fs, Encoding.UTF8);
                    List<VKS_EquipMentParameter> list = new List<VKS_EquipMentParameter>();
                    //每次读取一条数据
                    string nextLine;
                    //byte[] byEnc;
                    //byEnc = Convert.FromBase64String(sr.ReadLine());
                    string[] str;
                    while ((nextLine = sr.ReadLine()) != null)
                    {
                        VKS_EquipMentParameter ve = new VKS_EquipMentParameter();
                        str = nextLine.Split(‘,‘);
                        ve.Ramcode = str[0].ToString();
                        ve.ColTime = str[1].ToString();
                        ve.Vt = str[2].ToString();
                        ve.Q = str[3].ToString();
                        ve.P = str[4].ToString();
                        ve.T = str[5].ToString();
                        list.Add(ve);
                    }
                    sr.Close();
                    string a;
                    try
                    {
                        if (list.Count > 0)
                        {
                            try
                            {


                                if ((int)BKE.GetRamCodeList(list) > 0)
                                {
                                    // context.Response.Write("<script>alert(‘数据重复‘);</script>");
                                    a = "上传失败,数据重复";

                                }
                                else
                                {
                                    BKE.add(list);
                                    // context.Response.Write("<script>alert(‘导入成功‘);</script>");
                                    a = "导入成功";
                                }
                                return a;
                            }
                            catch (Exception ex)
                            {

                                throw;
                            }

                        }


                    }
                    catch (Exception ex)
                    {
                        context.Response.Write("执行错误");
                        throw;
                    }

                }

            }
            return "3";
        }

以上是关于文件的导入的主要内容,如果未能解决你的问题,请参考以下文章

CSV文件导入Mysql

plsql导入dmp文件存储过程需要删吗

怎么把csv文件导入mysql

怎么用plsql导入dmp文件

Eclipse如何导入文件

Java文件导入不了包,是怎么回事?