C# MVC实现前端上传文件保存到服务器

 后台代码

public string UploadECCInvoice_Intranet()
        {
            //返回前端结果状态对象
            StateClass sc = new StateClass();
            int resultZT = -1;
            HttpPostedFileBase file2 = Request.Files[0];

            HttpPostedFileBase file = Request.Files[0];
            Stream fileStr = file.InputStream;
            string fileName = file.FileName;
            string path_ECCInvoice = new FileInfo(fileName).FullName;

            sc.ztValues = resultZT;
            try
            {
                string destinationFile = path_ECCInvoice;//要上传的文件
                bool status = false;
                //连接  
                string serverFolder = @"\\192.168.3.66\电子竞价图纸";
                string PWD = "qwer.5678";//密码
                status = connectState(serverFolder, "ls", PWD);
                //status = connectState(serverFolder, "Everyone", "");
                if (status)
                {
                    //共享文件夹的目录  
                    DirectoryInfo theFolder = new DirectoryInfo(serverFolder);
                    string filename = theFolder.ToString();
                    //执行上传方法
                    //resultZT = UpLoadFiles(destinationFile, serverFolder, "ls", PWD);
                    sc = UpLoadFiles(file2, serverFolder, "ls", PWD);

                }
            }
            catch (Exception ex)
            {

            }
            return sc.ToJson();
        }

        /// <summary>  
        /// 连接远程共享文件夹  
        /// </summary>  
        /// <param name="path">远程共享文件夹的路径</param>  
        /// <param name="userName">用户名</param>  
        /// <param name="passWord">密码</param>  
        /// <returns></returns>  
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                proc.StandardInput.WriteLine("net use * /del /y");
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }







        public static StateClass UpLoadFiles(HttpPostedFileBase file, string urlPath, string User, string Pwd)
        {
            StateClass sate = new StateClass();
            int values = 99;
            sate.ztValues = values;
            try
            {
                //string newFileName = fileNamePath.Substring(fileNamePath.LastIndexOf(@"\") + 1);//取文件名称
                //if (urlPath.EndsWith(@"\") == false) urlPath = urlPath + @"\";

                //urlPath = urlPath + newFileName;

                WebClient myWebClient = new WebClient();

                NetworkCredential cread = new NetworkCredential();

                Stream fileStr = file.InputStream;

                urlPath = urlPath +"\\"+ file.FileName;

                myWebClient.Credentials = cread;
                //FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fileStr);

                try
                {
                    byte[] postArray = r.ReadBytes((int)fileStr.Length);
                    Stream postStream = myWebClient.OpenWrite(urlPath);
                    if (postStream.CanWrite)
                    {
                        postStream.Write(postArray, 0, postArray.Length);
                        sate.ztValues = 0;
                        sate.massege = "file:" + urlPath;
                    }
                    else
                    {
                    }

                    postStream.Close();
                }
                catch (Exception ex)
                {
                }
            }
            catch (Exception ex)
            {
            }
            return sate;
        }

前端代码

<div class="input_group">
            <input class="easyui-filebox" id="fj_file"  name="file" style="width:400px" data-options="labelWidth:220,label:'附件上传(jpg,png,gif,pdf):',buttonText:'附件上传',required:true,onChange:function(){updateLableFile(this)}">
        </div>

JS

    //添加时附件上传
    function updateLableFile(_this) {
        //alert($(_this).filebox('getValue'));
        var _imgsrc = $(_this).filebox('getValue');
         console.log(_imgsrc);
        var _file = $(_this).context.ownerDocument.activeElement.files[0];
        console.log(_file);
   
        var _fileUrl = getObjectUrl(_file);
        console.log(_fileUrl);
            _file.url = _fileUrl;
        var _fileName = _file.name;
        var fileType = _fileName.substr(_fileName.lastIndexOf("."));

        if (fileType != '.jpg' && fileType != '.png' && fileType != '.gif' &&  fileType != '.pdf') {
            $.messager.alert('提示信息', '请上传正确的附件', 'error');
            $(_this).val("")
            return false;
        } else {
                   var formData = new FormData();
            formData.append("files", _file);
                 debugger
                 $.ajax({
		        	        url: app.opt.url.inFile,
		        	        type: 'POST',
		        	        cache: false,
                            data: formData,
                            dataType: "json",
		        	        processData: false,
		        	        contentType: false,
		        	        beforeSend: function(){
                                modILload('数据正在上传中');
		        	        },
                            success: function (data) {
                                modilDisLoad();
                                debugger
                                if (data == '0') {
                                    
                                    $.messager.alert('提示信息', '导入成功!', 'info');
                                   
                                    
                                } else {
                                   $.messager.alert('提示信息', '导入失败', 'info');
                                }
                           }, error: function () {
                                   modilDisLoad();
                                   $.messager.alert('提示信息', '服务器错误!', 'info');
                            }
		        	    });
        }

    }
发布了16 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/beautifull001/article/details/90371475