C# Winform文件上传服务器

调用方法 HttpUploadFile(@"http://localhost:8099/Default.aspx", @"E:\工作记录\2017\2017年06月份工作计划.txt")


        /// <summary>   
        /// 将本地文件上传到指定的服务器(HttpWebRequest方法)   
        /// </summary>   
        /// <param name="address">文件上传到的服务器</param>   
        /// <param name="fileNamePath">要上传的本地文件(全路径)</param>   
        /// <param name="saveName">文件上传后的名称</param>   
        /// <returns>成功返回1,失败返回0</returns>   
        private static string HttpUploadFile(string address, string fileNamePath, string saveName = "")
        {
            int returnValue = 0;


            int pos = fileNamePath.LastIndexOf("\\");
            if (saveName == "")
                saveName = fileNamePath.Substring(pos + 1);


            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;
            string sReturnString = "";
            try
            {
                //每次上传4k  
                int bufferLength = 4096;
                byte[] buffer = new byte[bufferLength];
                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);
                    //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);
                sReturnString = sr.ReadLine();
                s.Close();
                sr.Close();
            }
            catch(Exception ex)
            {
                sReturnString = ex.Message;
            }
            finally
            {
                fs.Close();
                r.Close();
            } 
            return sReturnString;

        }




protected void Page_Load(object sender, EventArgs e)

        {
            if (Request.Files.Count > 0)
            {
                try
                {
                    HttpPostedFile file = Request.Files[0];
                    string filePath = "E:\\testupform\\" + file.FileName;
                    file.SaveAs(filePath);
                    Response.Write("Success");
                }
                catch
                {
                    Response.Write("上传文件失败");
                }
            }
            else
            {
                Response.Write("没有上传的文件");
            }
            Response.End();
        }
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
以下是C# WinForm上传文件的示例代码: ```csharp private void btnUpload_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); if (openFileDialog.ShowDialog() == DialogResult.OK) { string filePath = openFileDialog.FileName; string url = "http://localhost/UploadFileWeb/WebForm1.aspx"; string paramName = "file"; HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); request.ContentType = "multipart/form-data; boundary=" + boundary; using (Stream requestStream = request.GetRequestStream()) { requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n"; string header = string.Format(headerTemplate, paramName, Path.GetFileName(filePath)); byte[] headerBytes = Encoding.UTF8.GetBytes(header); requestStream.Write(headerBytes, 0, headerBytes.Length); using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } byte[] trailerBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n"); requestStream.Write(trailerBytes, 0, trailerBytes.Length); } using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string responseText = reader.ReadToEnd(); MessageBox.Show(responseText); } } } } ``` 该示例代码使用HttpWebRequest类向指定的URL上传文件。在上传文件之前,需要设置请求的Method为POST,ContentType为multipart/form-data,并设置请求头部的边界(boundary)。然后,将文件内容写入请求流中,最后发送请求并获取响应。在获取响应后,可以从响应流中读取服务器返回的内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值