How can I rewrite this CURL multipart/form-data request without using -F?

后端 未结 7 1479
无人共我
无人共我 2020-12-07 10:29

How can I rewrite the following CURL command, so that it doesn\'t use the -F option, but still generates the exact same HTTP request? i.e. so that it passes th

7条回答
  •  春和景丽
    2020-12-07 11:18

    This is what I'm using, I think it's clean and doesn't need temporary files nor gobbles up RAM in case you want to upload whole files (so no reading files into memory).

    # Set these two.
    file='path/to/yourfile.ext'
    url='http://endpoint.example.com/foo/bar'
    
    delim="-----MultipartDelimeter$$$RANDOM$RANDOM$RANDOM"
    nl=$'\r\n'
    mime="$(file -b --mime-type "$file")"
    
    # This is the "body" of the request.
    data() {
        # Also make sure to set the fields you need.
        printf %s "--$delim${nl}Content-Disposition: form-data; name=\"userfile\"${nl}Content-Type: $mime$nl$nl"
        cat "$file"
        printf %s "$nl--$delim--$nl"
    }
    
    # You can later grep this, or something.
    response="$(data | curl -# "$url" -H "content-type: multipart/form-data; boundary=$delim" --data-binary @-)"
    

提交回复
热议问题