HttpWebRequest C#上传文件

时间:2009-11-06 16:48:21

标签: c# file httpwebrequest uploading

使用C#,我正在尝试使用电子邮件营销客户端集成我的网上商店。我想每晚上传一个逗号分隔的订阅者文件。他们说为了让这个工作,它必须是一个表格帖子:multipart / form-data,但我没有使用表单。我能够连接到他们的服务器但我不断回来一个数据不能为空。谁能帮助我让这个工作?

public static string Create()
    {
        string authInfo = "username" + ":" + "password";

        string root = AppDomain.CurrentDomain.BaseDirectory;
        string file = root + "Folder\\work.txt";

        FileInfo fi = new FileInfo(file);
        int fileLength = (int)fi.Length;

        FileStream rdr = new FileStream(file, FileMode.Open);

        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
        httpWebRequest.Method = "POST";
        httpWebRequest.ContentType = "application/x-www-form-urlencoded";
        httpWebRequest.Accept = "application/xml";

        authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
        httpWebRequest.Headers["Authorization"] = "Basic " + authInfo;
        byte[] requestBytes = new byte[fileLength];

        int bytesRead = 0;
        httpWebRequest.ContentLength = requestBytes.Length;
        using (Stream requestStream = httpWebRequest.GetRequestStream())
        {
            while ((bytesRead = rdr.Read(requestBytes, 0, requestBytes.Length)) != 0)
            {
                requestStream.Write(requestBytes, 0, bytesRead);
                requestStream.Close();
            }
        }
        //READ RESPONSE FROM STREAM
        string responseData;
        using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream()))
        {
            responseData = responseStream.ReadToEnd();
            responseStream.Close();
        }
        return responseData;
    }

1 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,以下代码完全回答了这个问题:

//Identificate separator
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
//Encoding
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

//Creation and specification of the request
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url); //sVal is id for the webService
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = true;
wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sAuthorization = "login:password";//AUTHENTIFICATION BEGIN
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(sAuthorization);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
wr.Headers.Add("Authorization: Basic " + returnValue); //AUTHENTIFICATION END
Stream rs = wr.GetRequestStream();


string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}"; //For the POST's format

//Writting of the file
rs.Write(boundarybytes, 0, boundarybytes.Length);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(Server.MapPath("questions.pdf"));
rs.Write(formitembytes, 0, formitembytes.Length);

rs.Write(boundarybytes, 0, boundarybytes.Length);

string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "file", "questions.pdf", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);

FileStream fileStream = new FileStream(Server.MapPath("questions.pdf"), FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
    rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();

byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
rs = null;

WebResponse wresp = null;
try
{
    //Get the response
    wresp = wr.GetResponse();
    Stream stream2 = wresp.GetResponseStream();
    StreamReader reader2 = new StreamReader(stream2);
    string responseData = reader2.ReadToEnd();
}
catch (Exception ex)
{
    string s = ex.Message;
}
finally
{
    if (wresp != null)
    {
        wresp.Close();
        wresp = null;
    }
    wr = null;
}