从Windows窗体将文件上传到网站

我在执行此代码时遇到错误。当“内容类型”设置为其他格式时,请求不会通过

我已经浏览了该网站以及其他类似网站,以找到解决方案,但是我得到的所有示例都缺少一件事。 因此,我想出了我从一个在线站点合并的这段代码,但是返回给我的响应只是一个500:服务器错误。

下面的第一个代码在我的Windows窗体应用程序中。 每当我将内容类型更改为multipart/form-data时,请求就会到达接收端,该接收端是我已编程的网站。我在该方法上设置了一个断点,以便可以观看活动。但是这里的问题是没有文件发送到服务器 每当我更改Content-Type并放入application/x-www-form-urlencoded时,请求甚至根本不会发送到Web服务器

这是Windows窗体中的代码

private void Upload(string fileName = "2019116142944.avi")
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UploadUrl);
            request.Credentials = new NetworkCredential("anonymous","password");
            request.Headers.Add("fileName",System.IO.Path.GetFileName(fileName));
            request.ContentType = "text";//application/x-www-form-urlencoded
            request.Method = "POST";
            request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0";
            request.Host = "localhost";
            request.accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            request.SendChunked = true;
            request.TransferEncoding = "gzip,deflate,br";
            request.Referer = UploadUrl;
            request.Connection = "keep - alive";

            byte[] fileContent;
            using (StreamReader reader = new StreamReader(fileName))
            {
                fileContent = Encoding.UTF8.GetBytes(reader.ReadToEnd());
            }

            request.ContentLength = fileContent.Length;
            try
            {
                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(fileContent,fileContent.Length);
                }

                using (Httpwebresponse response = (Httpwebresponse)request.GetResponse())
                {
                    Console.WriteLine("FileUploaded");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

这是Web服务器接收端的代码

public object Stream(httppostedfileBase videoFile)
        {
            byte[] fileContent;

            if (Request.Files.Count != 0)
            {


                using (StreamReader reader = new StreamReader(Request.Files[0].InputStream))
                {
                    fileContent = Encoding.UTF8.GetBytes(reader.ReadToEnd());
                }
                Request.Headers.Getvalues("fileName").FirstOrDefault();
            var filePath = "/Uploads/files/";
            try
            {
                System.IO.File.WriteAllBytes(Server.MapPath(filePath) + "newfile.avi",fileContent);
            }
            catch (Exception ex)
            {
                string Message = ex.Message;
            }
            }
            return null;
        }
liningoo 回答:从Windows窗体将文件上传到网站

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3147994.html

大家都在问