分 享

【凤凰社】.Net开发winform程序实现文件的上传与下载功能

可以写在自己的工具类里,方便调用。

实现上传下载功能代码:

        /// <summary>   
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法)   
        /// </summary>   
        /// <param name="address">文件上传到的服务器</param>   
        /// <param name="fileNamePath">要上传的本地文件(全路径)</param>   
        /// <param name="saveName">文件上传后的名称</param>   
        /// <param name="progressBar">上传进度条</param>   
        /// <returns></returns>   
        public static void Upload_Request2(string address, string fileNamePath, string saveName, ProgressBar progressBar)
        {
            if (saveName == "") {
                saveName = fileNamePath.Substring(fileNamePath.LastIndexOf("\\") + 1);
            }
            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("\r\n--" + strBoundary + "\r\n");     //请求头部信息   
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append("file");
            sb.Append("\"; filename=\"");
            sb.Append(saveName);
            sb.Append("\";");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string strPostHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);     // 根据uri创建HttpWebRequest对象   
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(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
            {
                progressBar.Maximum = int.MaxValue;
                progressBar.Minimum = 0;
                progressBar.Value = 0;
                //每次上传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;
                    progressBar.Value = (int)(offset * (int.MaxValue / length));
                    TimeSpan span = DateTime.Now - startTime;
                    double second = span.TotalSeconds;
                    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")
                {
                    MessageBox.Show("上传成功", "Success");
                }
                else if (sReturnString == "Error")
                {
                    MessageBox.Show("上传失败", "Error");
                }
            }
            catch
            {
                MessageBox.Show("上传失败", "Error");
            }
            finally
            {
                fs.Close();
                r.Close();
            }
            
        }
        /// <summary>
        /// Http方式下载文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public static void Download(string url, string localfile)
        {
            long startPosition = 0; // 上次下载的文件起始位置
            FileStream writeStream; // 写入本地文件流对象
            try
            {
                // 判断要下载的文件夹是否存在
                if (File.Exists(localfile))
                {

                    writeStream = File.OpenWrite(localfile);             // 存在则打开要下载的文件
                    startPosition = writeStream.Length;                  // 获取已经下载的长度
                    writeStream.Seek(startPosition, SeekOrigin.Current); // 本地文件写入位置定位
                }
                else
                {
                    writeStream = new FileStream(localfile, FileMode.Create);// 文件不保存创建一个文件
                    startPosition = 0;
                }


                try
                {
                    HttpWebRequest myRequest = (HttpWebRequest)HttpWebRequest.Create(url);// 打开网络连接

                    if (startPosition > 0)
                    {
                        myRequest.AddRange((int)startPosition);// 设置Range值,与上面的writeStream.Seek用意相同,是为了定义远程文件读取位置
                    }


                    Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服务器请求,获得服务器的回应数据流


                    byte[] btArray = new byte[512];// 定义一个字节数据,用来向readStream读取内容和向writeStream写入内容
                    int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向远程文件读第一次

                    while (contentSize > 0)// 如果读取长度大于零则继续读
                    {
                        writeStream.Write(btArray, 0, contentSize);// 写入本地文件
                        contentSize = readStream.Read(btArray, 0, btArray.Length);// 继续向远程文件读取
                    }

                    //关闭流
                    writeStream.Close();
                    readStream.Close();
                    MessageBox.Show("下载成功", "Success");
                }
                catch (Exception exp)
                {
                    writeStream.Close();
                    MessageBox.Show(exp.Message, "Error");   //返回false下载失败
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message, "Error");   //返回false下载失败
            }
        }

winform使用代码:

上传:

private void btn_up_Click(object sender, EventArgs e)
{
   //WebUtil是我的工具类名称,是设计界面创建的progressBar进度条控件
   WebUtil.Upload_Request2(uriString, this.txtFile.Text,"", progressBar1);
}

下载:

private void btn_Down_Click(object sender, EventArgs e)
{
    //被下载的文件地址,绝对路径
    string url = uriString + this.txtDownFileName.Text;
    WebUtil.Download(url, this.txtPath.Text + this.txtDownFileName.Text);
}

Web端接收代码(随便创建一个aspx文件,写在里面):

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Files.Count > 0)
        {
            try
            {
                HttpPostedFile file = Request.Files[0];
                //配置存放路径
                string filePath = Server.HtmlEncode(Request.PhysicalApplicationPath) + "\\upload\\Document\\" + file.FileName;
                file.SaveAs(filePath);
                Response.Write("Success");
            }
            catch
            {
                Response.Write("Error");
            }
        }
        else
        {
            Response.Write("Error1");
        }

    }

以上就是.Net开发winform程序实现文件的上传与下载功能的全部代码,注释给的很清楚了,如果还有不明白的可以在下方评论,我会及时回复的!



0 评论

回复