如何使用多个文件解析XHR multipart / form-data请求

时间:2016-09-09 18:43:00

标签: c# wcf kendo-upload

我在网上看过多个多部分/表单数据解析器的例子,但它们都不能在我的网站上运行。我使用Kendo上传控件设置为异步模式并启用批量上传,生成的请求如下所示:

BOUNDARY
Content-Disposition: form-data; name="Param_1"

Param_1 Value
BOUNDARY
Content-Disposition: form-data; name="Param_2"

Param_2 Value
BOUNDARY
Content-Disposition: form-data; name="files[]"; filename="A.docx"
Content-Type: application/octet-stream

[Binary Data Here]
BOUNDARY
Content-Disposition: form-data; name="files[]"; filename="B.docx"
Content-Type: application/octet-stream

[Binary Data Here]
BOUNDARY--

我在网上找到的每个库都成功检索了参数和第一个文件,但是有些从未看到第二个文件和那些保存不正确的文件。在SO WCF multipart/form data with multiple files上有一个类似的问题,但该解决方案仅适用于文本文件而非二进制文件。

1 个答案:

答案 0 :(得分:1)

其他解决方案对二进制文件的问题在于,他们将响应转换为字符串以解析它,然后将该字符串转换回文件,这不适用于二进制数据。我提出了一个解决方案,而不是将响应转换为字符串来解析它,我将其保留为byte []并使用找到的代码here将其分隔为字节[]。完成后,将每个部分转换为字符串以查看它是参数还是文件,如果它是参数,则读取它,否则将其写为文件。下面是工作代码,假设您将Stream作为byte []并将分隔符作为字符串:

// given byte[] streamByte, String delimiterString, and Encoding encoding
Regex regQuery;
Match regMatch;
string propertyType;

byte[] delimiterBytes = encoding.GetBytes(delimiterString);
byte[] delimiterWithNewLineBytes = encoding.GetBytes(delimiterString + "\r\n");
// the request ends DELIMITER--\r\n
byte[] delimiterEndBytes = encoding.GetBytes("\r\n" + delimiterString + "--\r\n");
int lengthDifferenceWithEndBytes = (delimiterString + "--\r\n").Length;

// seperate by delimiter + newline
// ByteArraySplit code found at https://stackoverflow.com/a/9755250/4244411
byte[][] separatedStream = ByteArraySplit(streamBytes, delimiterWithNewLineBytes);
streamBytes = null;
for (int i = 0; i < separatedStream.Length; i++)
{
    // parse out whether this is a parameter or a file
    // get the first line of the byte[] as a string
    string thisPieceAsString = encoding.GetString(separatedStream[i]);

    if (string.IsNullOrWhiteSpace(thisPieceAsString)) { continue; }

    string firstLine = thisPieceAsString.Substring(0, thisPieceAsString.IndexOf("\r\n"));

    // Check the item to see what it is
    regQuery = new Regex(@"(?<=name\=\"")(.*?)(?=\"")");
    regMatch = regQuery.Match(firstLine);
    propertyType = regMatch.Value.Trim();

    // get the index of the start of the content and the end of the content
    int indexOfStartOfContent = thisPieceAsString.IndexOf("\r\n\r\n") + "\r\n\r\n".Length;

    // this line compares the name to the name of the html input control, 
    // this can be smarter by instead looking for the filename property
    if (propertyType != "files")
    {
        // this is a parameter!
        // if this is the last piece, chop off the final delimiter
        int lengthToRemove = (i == separatedStream.Length - 1) ? lengthDifferenceWithEndBytes : 0;
        string value = thisPieceAsString.Substring(indexOfStartOfContent, thisPieceAsString.Length - "\r\n".Length - indexOfStartOfContent - lengthToRemove);
        // do something with the parameter
    }
    else
    {
        // this is a file!
        regQuery = new Regex(@"(?<=filename\=\"")(.*?)(?=\"")");
        regMatch = regQuery.Match(firstLine);
        string fileName = regMatch.Value.Trim();

        // get the content byte[]
        // if this is the last piece, chop off the final delimiter
        int lengthToRemove = (i == separatedStream.Length - 1) ? delimiterEndBytes.Length : 0;
        int contentByteArrayStartIndex = encoding.GetBytes(thisPieceAsString.Substring(0, indexOfStartOfContent)).Length;
        byte[] fileData = new byte[separatedStream[i].Length - contentByteArrayStartIndex - lengthToRemove];
        Array.Copy(separatedStream[i], contentByteArrayStartIndex, fileData, 0, separatedStream[i].Length - contentByteArrayStartIndex - lengthToRemove);
        // save the fileData byte[] as the file
    }

}