编程语言
首页 > 编程语言> > HttpWebRequest C#上传文件

HttpWebRequest C#上传文件

作者:互联网

使用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;
    }

解决方法:

我遇到了同样的问题,下面的代码完美地解决了这个问题:

//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;
}

标签:file,httpwebrequest,uploading,c
来源: https://codeday.me/bug/20191107/2002446.html