如何保存通过HTML表单字段提交的二进制文件?

时间:2012-09-05 21:46:58

标签: c# cgi binaryfiles html-form

我需要将一个函数添加到用C#编写的现有CGI应用程序作为Windows控制台应用程序。我需要为少数用户添加能够提交数据文件进行处理的能力。数据文件可以是text / csv文件或各种二进制文件(.xls,.pdf)。我有一个简单的测试HTML表单,使用一个字段来设置选择/提交文件。一切正常。我可以在服务器上保存文本文件没有问题。但是如何保存二进制文件?我确信这很容易,但我一直无法理解。

以下是一些用于保存文本文件的示例代码:

String formData = Console.In.ReadToEnd();
string boundary = string.Empty;
string[] cPairs = cType.Split(new string[] { "; " }, StringSplitOptions.None);
foreach (string pair in cPairs) {
    //finds the 'boundary' text
    if (pair.Contains("boundary"))
        boundary = "--" + pair.Split('=')[1];
}

//splits on the 'boundary' to get individual form fields/sections
string[] sections = rawParams.Split(new string[] { boundary }, StringSplitOptions.RemoveEmptyEntries);

// parse each section
foreach (string section in sections) {
    string[] parts = section.Split(new string[] { "; ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
    if (parts[1].Equals("name=\"dFile\"")) { // 'dFile' is the form field-name for the datafile
        //below lines get the filename
        Regex regx = new Regex("filename=\"(.+)\"", RegexOptions.IgnoreCase);
        Match fPath = regx.Match(parts[2]);
        FileInfo fi = new FileInfo(fPath.Groups[1].Value);
        regx = new Regex("([-A-Z0-9_ .]+)", RegexOptions.IgnoreCase);
        Match fname = regx.Match(fi.Name);

        //below lines save the file contents to a text file; starts at index 4 of the 'parts' array
        if (fname.Groups[1].Success) {
            TextWriter tw = new StreamWriter(fname.Groups[1].Value);
            for (int i = 4; i < parts.Length; i++) {
                tw.WriteLine(parts[i]);
            }
            tw.Close();
        }
    }
    else {
        // parse other non-file form fields
    }
}

关键部分是保存到文件。我如何为二进制文件执行此操作?    戴夫

1 个答案:

答案 0 :(得分:0)

如果您只想将某些数据转储到二进制文件,请使用以下内容:

FileStream fs = File.Create(fname.Groups[1].Value, SOME_SIZE, FileOptions.None))
BinaryFormatter formatter = new BinaryFormatter();
...
//inside your loop
string s = parts[i];
formatter.Serialize(fs, Encoding.Unicode.GetBytes(s));

显然GetBytes()使用了正确的编码。

所以你的代码看起来像这样:

String formData = Console.In.ReadToEnd();
string boundary = string.Empty;
string[] cPairs = cType.Split(new string[] { "; " }, StringSplitOptions.None);
foreach (string pair in cPairs) {
//finds the 'boundary' text
if (pair.Contains("boundary"))
    boundary = "--" + pair.Split('=')[1];
}

//splits on the 'boundary' to get individual form fields/sections
string[] sections = rawParams.Split(new string[] { boundary }, StringSplitOptions.RemoveEmptyEntries);

// parse each section
foreach (string section in sections) {
string[] parts = section.Split(new string[] { "; ", Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (parts[1].Equals("name=\"dFile\"")) { // 'dFile' is the form field-name for the datafile
    //below lines get the filename
    Regex regx = new Regex("filename=\"(.+)\"", RegexOptions.IgnoreCase);
    Match fPath = regx.Match(parts[2]);
    FileInfo fi = new FileInfo(fPath.Groups[1].Value);
    regx = new Regex("([-A-Z0-9_ .]+)", RegexOptions.IgnoreCase);
    Match fname = regx.Match(fi.Name);

    FileStream fs = File.Create(fname.Groups[1].Value, SOME_SIZE, FileOptions.None))
    BinaryFormatter formatter = new BinaryFormatter();

    //below lines save the file contents to a text file; starts at index 4 of the 'parts' array
    if (fname.Groups[1].Success) {
        for (int i = 4; i < parts.Length; i++) {
            string s = parts[i];
            formatter.Serialize(fs, Encoding.Unicode.GetBytes(s));
        }
    }
}
else {
    // parse other non-file form fields
}

}