【问题标题】:Uploading a file and a string to http then getting the response将文件和字符串上传到 http 然后获取响应
【发布时间】:2013-03-11 20:16:29
【问题描述】:

基本上我有一个服务器可以让你上传文件,但它需要登录,所以当我从客户端上传时,我不仅需要发送要上传的文件,还需要将用户名和密码作为字符串发送,然后读取来自服务器的响应。我已尽力而为,但出现错误“您必须在调用 [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);

【问题讨论】:

  • 为什么不使用Credentials 作为Authenticate 标头传递用户名和密码?让主体完全二元化。
  • 因为我不知道你如何在 php 中处理凭据等。

标签: c# upload


【解决方案1】:

也许它不喜欢 2 个帖子?可以将它们连接起来并立即发送。

void Main()
{
byte[] login = BitConverter.GetBytes("loginstring");
byte[] img = BitConverter.GetBytes("fakeimagedataherereplacewithrealbytes");
byte[] tosend = login.Concat(img).ToArray();
using(WebRequest wr = WebRequest.Create("someurl"))
{
    using (Stream rs = wr.GetRequestStream())
    {
        rs.Write(LoginBytes, 0, LoginBytes.Length);
        //...whatever
    }

}

}

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2013-06-29
    • 2018-05-15
    • 1970-01-01
    相关资源
    最近更新 更多