以块为单位拆分文件,然后通过边界上传

时间:2014-03-19 20:47:00

标签: c# .net chunked

我试图将一些文件上传到服务器。

我的代码如下:

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的文件应该以块的形式分割,然后发送到服务器。但我不知道如何拆分文件然后发送到服务器...

0 个答案:

没有答案