0

我正在尝试将一些文件上传到服务器。

我的代码如下所示:

public void HttpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc, string cookie)
{
try
{
    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    SetStatus("Making request");
    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.Headers["Cookie"] = cookie;
    wr.KeepAlive = true;
    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

    Stream rs = wr.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    SetStatus("Parsing values");
    foreach (string key in nvc.Keys)
    {
        rs.Write(boundarybytes, 0, boundarybytes.Length);
        string formitem = string.Format(formdataTemplate, key, nvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes, 0, formitembytes.Length);
    }
    rs.Write(boundarybytes, 0, boundarybytes.Length);

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

    FileStream fileStream = new FileStream(file, 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();

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

    HttpWebResponse wresp = null;
    wresp = (HttpWebResponse)wr.GetResponse();
    if (wresp.StatusCode != HttpStatusCode.OK)
    {
        throw new Exception("File was not uploaded successfully.");
    }
    SetStatus("Success");
}
catch
{
    statusLabel.ForeColor = Color.Red;
    SetStatus("Failure");
}

}

以这种方式调用它:

void uploader_DoWork2(object sender, DoWorkEventArgs e)
{
    NameValueCollection c = new NameValueCollection();
    c.Add("chunk", "0");
    c.Add("name", Path.GetFileName(filenameBox.Text));
    c.Add("chunks", "1");
    HttpUploadFile("https://site.com/upload.php", filenameBox.Text, "file", GetContentType(filenameBox.Text), c, loginCookies);
}

该脚本工作正常,如果文件小于 2MB,则会上传文件。如果文件大于 2MB,即使文件没有成功上传也会返回成功。我认为大于 2MB 的文件应该分成块然后发送到服务器。但我不知道如何拆分文件然后分块发送到服务器......

4

0 回答 0