Requests
Requests copied to clipboard
Add ability to pass in a file pointer
How to post file data / upload file using requests? I can;t find any documentation on this.
Like in HttpRequest
, we have a method called addPostFile()
There's no native way to pass files in, you'll need to pass a string in via the data
parameter. See the making a POST request section of the docs.
I'll just add (while writing code that needs to post 20 meg CSV files to a remote server), that it would be nice if the data
parameter accepted a file pointer resource -- or maybe better, an SPLFileObject -- and then used the contents of that for the request body.
Otherwise, you need to load the whole file into memory in order to pass it as the request.
Reopened, as that is a good point. Whether that's technically possible in the transports, I'm not sure.
In terms of API design, I think ideally:
- If
data
is a string, we simply pass the string as file data. - If
data
is a file resource, we usefread
and family - If
data
is a SplFileObject, we use$data->current()
in a loop
I'm not sure, but I feel like we should be able to handle cases 2 and 3 in the same way. It doesn't seem like fread
accepts an SplFileObject unfortunately, so we probably have to go in the opposite direction. I'd prefer to work with bytes, but it looks like SplFileObject works line-by-line.
Based on PHP bug #36289, it looks like SplFileObject is unsuitable for this. I'd prefer to write a file-like interface and wrap file resources suitably instead.
Hrm, I never noticed that SplFileObject wasn't useful for binary files .. good to know.
As for the actual upload, would it not be something like this pseudocoe (at least as far as the cURL transport is concerned):
if ( get_resource_type($data) == 'stream' ) {
curl_setopt($ch, CURLOPT_INFILE, $data);
// kludge to get size of file when only given the resource
fseek ( $data, 0, SEEK_END );
$size = ftell($data);
curl_setopt($ch, CURLOPT_INFILESIZE, $size );
rewind($data);
}
Anything new about this? I need to upload a file via post as well.
I'm also interested in this.
Any progress here?
Not yet available in the last build. I'm interested in it too.
PHP 5.5 now has CurlFile support: https://secure.php.net/manual/en/class.curlfile.php
Anyone have a fork making this work?
I just shifted to guzzle, which is doing really well in terms of development.
Yeah, but the main selling point of this library was 5.2 compatibility (not my decision!) which Guzzle doesn't offer.
Related #289