Generating multipart boundary

青春壹個敷衍的年華 提交于 2019-12-17 22:19:18

问题


I'm writing a script that uploads a file to a cgi script that expects a multipart request, such as a form on a HTML page. The boundary is a unique token that annotates the file contents in the request body. Here's an example body:

--BOUNDARY
Content-Disposition: form-data; name="paramname"; filename="foo.txt"
Content-Type: text/plain

... file contents here ...
--BOUNDARY--

The boundary cannot be present in the file contents, for obvious reasons.

What should I do in order to create an unique boundary? Should I generate a random string, check to see if it is in the file contents, and if it is, generate a new, rinse and repeat, until I have a unique string? Or would a "pretty random token" (say, combination of timestamp, process id, etc) be enough?


回答1:


If you use something random enough like a GUID there shouldn't be any need to hunt through the payload to check for an alias of the boundary. Something like:-

----=NextPart_3676416B-9AD6-440C-B3C8-FC66DDC7DB45
Header:....

Payload
----=NextPart_3676416B-9AD6-440C-B3C8-FC66DDC7DB45--




回答2:


For Java guys :

protected String generateBoundary() {
             StringBuilder buffer = new StringBuilder();
             Random rand = new Random();
             int count = rand.nextInt(11) + 30; // a random size from 30 to 40
             for (int i = 0; i < count; i++) {
             buffer.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
             }
             return buffer.toString();
        }

private final static char[] MULTIPART_CHARS =
             "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
                  .toCharArray();

Reference url : http://hc.apache.org/httpcomponents-client-ga/httpmime/xref/org/apache/http/entity/mime/MultipartEntity.html




回答3:


And for the Swift people (to balance the Java):

func createBoundaryString() -> String {
    var str = ""
    let length = arc4random_uniform(11) + 30
    let charSet = [Character]("-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

    for _ in 0..<length {
        str.append(charSet[Int(arc4random_uniform(UInt32(charSet.count)))])
    }
    return str
}



回答4:


If you are feeling paranoid, you can generate a random boundary and search for it in the string to be sent, append random char (or re-create new) on find, repeat. But my experience is any arbitrary non-dictionary string of 10 or so characters is about impossible to occur, so picking something like ---BOUNDARY---BOUNDARY---BOUNDARY--- is perfectly sufficient.



来源:https://stackoverflow.com/questions/2071257/generating-multipart-boundary

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!