Add ability to pass in a file pointer #34

Open
sidchilling opened this Issue Nov 30, 2012 · 13 comments

Comments

Projects
None yet
9 participants

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()

Owner

rmccue commented Dec 1, 2012

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.

rmccue closed this Dec 1, 2012

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.

rmccue reopened this Mar 12, 2013

Owner

rmccue commented Mar 12, 2013

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:

  1. If data is a string, we simply pass the string as file data.
  2. If data is a file resource, we use fread and family
  3. 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.

Owner

rmccue commented Mar 12, 2013

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.

motdotla commented Nov 1, 2013

I'm also interested in this.

Any progress here?

Not yet available in the last build. I'm interested in it too.

Anyone have a fork making this work?

captn3m0 commented Mar 5, 2016

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.

@rmccue rmccue modified the milestone: 1.7, 1.8 Jul 28, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment