What is the correct way of sending large file through HTTP POST, without loading the whole file into ram?

前端 未结 3 1665
感情败类
感情败类 2021-02-01 08:45

I\'m currently working on an application for uploading large video files from the iPhone to a webservice through simple http post. As of right now, I build an NSURLRequest and p

相关标签:
3条回答
  • 2021-02-01 09:27

    You can use a NSInputStream to provide the data to post via -[NSMutableURLRequest setHTTPBodyStream:]. This could be an input stream that reads from a file. You might need to implement the connection:needNewBodyStream: method in your URL connection delegate to provide a new, unopened stream in case the system needs to retransmit the data.

    0 讨论(0)
  • 2021-02-01 09:30

    One way to do this is to use an asynchronous NSInputStream in concert with a file. When the asynchronous connection asks you to provide more data, you read in the data from a file. You have a few ways to do this:

    • UNIX/BSD interface. use open (or fopen), malloc, read, and create a NSData object from the malloced data

    • use the above with mmap() if you know it

    • use the Foundation class NSFileHandle APIs to do more or less the same using ObjectiveC

    You can read up on streams in the 'Stream Programming Guide'. If this doesn't work for you there are lots of open source projects that can upload files, for instance MKNetworkKit

    0 讨论(0)
  • 2021-02-01 09:37

    You can use NSInputStream on NSMutableURLRequest. For example:

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
    NSInputStream *stream = [[NSInputStream alloc] initWithFileAtPath:filePath];
    [request setHTTPBodyStream:stream];
    [request setHTTPMethod:@"POST"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
    }];
    
    0 讨论(0)
提交回复
热议问题