基本上我有一个服务器可以让你上传文件,但它需要登录,所以当我从客户端上传时,我不仅需要发送要上传的文件,还需要将用户名和密码作为字符串发送,然后读取来自服务器。我已尽力而为,但出现错误“您必须在调用 [Begin]GetResponse 之前将 ContentLength 字节写入请求流。”
我上传图片的代码:
string ImgFile = Path.GetTempFileName();
img.Save(ImgFile);
byte[] LoginBytes = ASCIIEncoding.ASCII.GetBytes("username=" + Username + "&password=" + Password);
byte[] ImageBytes = File.ReadAllBytes(ImgFile);
int ByteLen = LoginBytes.Length + ImageBytes.Length;
WebRequest ReqResponse = WebRequest.Create(url);
ReqResponse.Credentials = CredentialCache.DefaultCredentials;
ReqResponse.Proxy = WebRequest.DefaultWebProxy;
ReqResponse.Proxy.Credentials = CredentialCache.DefaultCredentials;
ReqResponse.Method = "POST";
ReqResponse.ContentType = "application/x-www-form-urlencoded";
ReqResponse.ContentLength = ByteLen;
ReqResponse.GetRequestStream().Write(LoginBytes, 0, LoginBytes.Length);
ReqResponse.GetRequestStream().Write(ImageBytes, 0, ImageBytes.Length);
string response = (new StreamReader(ReqResponse.GetResponse().GetResponseStream()).ReadToEnd());
MessageBox.Show(response);