zoukankan      html  css  js  c++  java
  • winform程序压缩文件上传,服务器端asp.net mvc进行接收解压

    期间编程没什么难度,唯一可能忽略导致结果失败是asp.net  mvc配置

    对于压缩文件大的话,需要配置mvc的最大接收量:

      <system.web>
        <httpRuntime maxRequestLength="2147483647" executionTimeout="3600" />    <!--允许上传数据大小->
      </system.web>
    
    
    
     <system.webServer>
        <!--允许上传文件长度,单位字节-->
        <security>
           <requestFiltering>
            <requestLimits maxAllowedContentLength="2147483647"/>
          </requestFiltering>
        </security>
     </system.webServer>
    

      

    winform中压缩和上传:

    调用部分如下:

    string proPath = Application.StartupPath + "\temp\product\" + project.ProjectName;
    ZipFile(proPath,proPath + ".zip");//压缩
    
    var uploadResult = Upload_Request(WebConfig.UploadUrl + "/Mobile/ReceiveProjectFile", proPath + ".zip",
    project.ProjectName + ".zip");//上传
    if (uploadResult == 0)
    {
    LoadingForm.CloseLoadingCircle();
    Notification t = new Notification("方案附件上传失败,请重试!", 3, FormAnimator.AnimationMethod.Slide, FormAnimator.AnimationDirection.Up, true, "error");
    t.Show();
    return;
    }
    File.Delete(proPath + ".zip");
    

     

    /// <summary>
            /// 压缩文件
            /// </summary>
            /// <param name="strFile">待压缩文件路径</param>
            /// <param name="strZip">压缩文件路径</param>
            public void ZipFile(string strFile, string strZip)
            {
                if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)
                    strFile += Path.DirectorySeparatorChar;
                ZipOutputStream s = new ZipOutputStream(File.Create(strZip));
                s.SetLevel(6); // 0 - store only to 9 - means best compression
                zip(strFile, s, strFile);
                s.Finish();
                s.Close();
            }
    
            private void zip(string strFile, ZipOutputStream s, string staticFile)
            {
                if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar) strFile += Path.DirectorySeparatorChar;
                Crc32 crc = new Crc32();
                string[] filenames = Directory.GetFileSystemEntries(strFile);
                foreach (string file in filenames)
                {
    
                    if (Directory.Exists(file))
                    {
                        zip(file, s, staticFile);
                    }
    
                    else // 否则直接压缩文件
                    {
                        //打开压缩文件
                        FileStream fs = File.OpenRead(file);
    
                        byte[] buffer = new byte[fs.Length];
                        fs.Read(buffer, 0, buffer.Length);
                        string tempfile = file.Substring(staticFile.LastIndexOf("\") + 1);
                        ZipEntry entry = new ZipEntry(tempfile);
    
                        entry.DateTime = DateTime.Now;
                        entry.Size = fs.Length;
                        fs.Close();
                        crc.Reset();
                        crc.Update(buffer);
                        entry.Crc = crc.Value;
                        s.PutNextEntry(entry);
    
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
            }
    

      

    /// <summary>
            /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
            /// </summary>
            /// <param name="address">文件上传到的服务器</param>
            /// <param name="fileNamePath">要上传的本地文件(全路径)</param>
            /// <param name="saveName">文件上传后的名称</param>
            /// <returns>成功返回1,失败返回0</returns>
            private int Upload_Request(string address, string fileNamePath, string saveName)
            {
                int returnValue = 0;
                // 要上传的文件
                FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);
                //时间戳
                string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
                byte[] boundaryBytes = Encoding.ASCII.GetBytes("
    --" + strBoundary + "
    ");
                //请求头部信息
                StringBuilder sb = new StringBuilder();
                sb.Append("--");
                sb.Append(strBoundary);
                sb.Append("
    ");
                sb.Append("Content-Disposition: form-data; name='");
                sb.Append("file");
                sb.Append("'; filename=");
                sb.Append(saveName);
                sb.Append("'");
                sb.Append("
    ");
                sb.Append("Content-Type: ");
                sb.Append("application/octet-stream");
                sb.Append("
    ");
                sb.Append("
    ");
                string strPostHeader = sb.ToString();
                byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
                // 根据uri创建HttpWebRequest对象
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(address);
                httpReq.Method = "POST";
                //对发送的数据不使用缓存
                httpReq.AllowWriteStreamBuffering = false;
                //设置获得响应的超时时间(300秒)
                httpReq.Timeout = 300000;
                httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
                long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
                long fileLength = fs.Length;
                httpReq.ContentLength = length;
                try
                {
                    //每次上传4k
                    int bufferLength = 4096;
                    byte[] buffer = new byte[bufferLength];
                    //已上传的字节数
                    long offset = 0;
                    //开始上传时间
                    DateTime startTime = DateTime.Now;
                    int size = r.Read(buffer, 0, bufferLength);
                    Stream postStream = httpReq.GetRequestStream();
                    //发送请求头部消息
                    postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                    while (size > 0)
                    {
                        postStream.Write(buffer, 0, size);
                        offset += size;
                        Application.DoEvents();
                        size = r.Read(buffer, 0, bufferLength);
                    }
                    //添加尾部的时间戳
                    postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    postStream.Close();
                    //获取服务器端的响应
                    WebResponse webRespon = httpReq.GetResponse();
                    Stream s = webRespon.GetResponseStream();
                    StreamReader sr = new StreamReader(s);
                    //读取服务器端返回的消息
                    String sReturnString = sr.ReadLine();
                    s.Close();
                    sr.Close();
                    if (sReturnString == "Success")
                    {
                        returnValue = 1;
                    }
                    else if (sReturnString == "Error")
                    {
                        returnValue = 0;
                    }
                }
                catch
                {
                    returnValue = 0;
                }
                finally
                {
                    fs.Close();
                    r.Close();
                }
                return returnValue;
            }
    

      

    asp.net mvc接收压缩包,并解压:

    /// <summary>
            /// 接收文件压缩包
            /// </summary>
            /// <returns></returns>
            [HttpPost]
            public ContentResult ReceiveProjectFile()
            {
    
                var result = "Success";
                try
                {
                    if (Request.Files.Count < 1)
                    {
                        result = "Error";
                        return Content(result);;
                    }
                    HttpPostedFileBase file = Request.Files[0];
                    string filePath = Server.MapPath("~/SERVER") + "/" + file.FileName;
                    file.SaveAs(filePath);
                    unZipFile(filePath, Server.MapPath("~/SERVER") + "/" + file.FileName.Substring(0,file.FileName.IndexOf(".zip")));
                }
                catch (Exception)
                {
                    result = "Error";
                }
    
                return Content(result);
            }
    

      

     /// <summary>
            /// 
            /// </summary>
            /// <param name="TargetFile">待解压文件</param>
            /// <param name="fileDir">解压路径</param>
            /// <returns></returns>
            public string unZipFile(string TargetFile, string fileDir)
            {
                string rootFile = " ";
                try
                {
                    //读取压缩文件(zip文件),准备解压缩
                    ZipInputStream s = new ZipInputStream(System.IO.File.OpenRead(TargetFile.Trim()));
                    ZipEntry theEntry;
                    string path = fileDir;
                    //解压出来的文件保存的路径
    
                    string rootDir = " ";
                    //根目录下的第一个子文件夹的名称
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        rootDir = Path.GetDirectoryName(theEntry.Name);
                        //得到根目录下的第一级子文件夹的名称
                        if (rootDir.IndexOf("\") >= 0)
                        {
                            rootDir = rootDir.Substring(0, rootDir.IndexOf("\") + 1);
                        }
                        string dir = Path.GetDirectoryName(theEntry.Name);
                        //根目录下的第一级子文件夹的下的文件夹的名称
                        string fileName = Path.GetFileName(theEntry.Name);
                        //根目录下的文件名称
                        if (dir != " ")
                        //创建根目录下的子文件夹,不限制级别
                        {
                            if (!Directory.Exists(fileDir + "\" + dir))
                            {
                                path = fileDir + "\" + dir;
                                //在指定的路径创建文件夹
                                Directory.CreateDirectory(path);
                            }
                        }
                        else if (dir == " " && fileName != "")
                        //根目录下的文件
                        {
                            path = fileDir;
                            rootFile = fileName;
                        }
                        else if (dir != " " && fileName != "")
                        //根目录下的第一级子文件夹下的文件
                        {
                            if (dir.IndexOf("\") > 0)
                            //指定文件保存的路径
                            {
                                path = fileDir + "\" + dir;
                            }
                        }
    
                        if (dir == rootDir)
                        //判断是不是需要保存在根目录下的文件
                        {
                            path = fileDir + "\" + rootDir;
                        }
    
                        //以下为解压缩zip文件的基本步骤
                        //基本思路就是遍历压缩文件里的所有文件,创建一个相同的文件。
                        if (fileName != String.Empty)
                        {
                            FileStream streamWriter = System.IO.File.Create(path + "\" + fileName);
    
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
    
                            streamWriter.Close();
                        }
                    }
                    s.Close();
                    System.IO.File.Delete(TargetFile);
                    return rootFile;
                }
                catch (Exception ex)
                {
                    return "1; " + ex.Message;
                }
            }   
    

      

     

  • 相关阅读:
    String 方法
    异常处理
    数组长度改变方法
    对象
    重载(函数)
    函数
    java基础(死循环退出选项)
    cookie的封装,获取,删除
    事件监听的理解
    JS少数兼容
  • 原文地址:https://www.cnblogs.com/y114113/p/7785033.html
Copyright © 2011-2022 走看看