NSURLConnection Unable to http post large file

2019-08-25 04:34发布

问题:

We are trying to add in functionality into our app to allow it to POST a large file approx 50kb to our web service the file itself is a HTML template, however with the code below what we are finding is that the data seems to get cut off when the web service saves it.

The web service is currently designed to check the $_POST['html'] variable and write it to a file.

Is there a better way to do this and does anyone have any idea why the upload is not complete?

Thanks Aaron

   NSString *myText;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"template" ofType:@"htm"];  
    if (filePath) {  
        myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; 
    } 

    NSURL *URL = [NSURL URLWithString:@"http://mywebsiteurl.com/receiveData.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"POST";
    NSString *params = [NSString stringWithFormat:@"html=%@", myText];

    NSData *data = [params dataUsingEncoding:NSASCIIStringEncoding];
    [request addValue:@"8bit" forHTTPHeaderField:@"Content-Transfer-Encoding"];
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request addValue:[NSString stringWithFormat:@"%i", [data length]] forHTTPHeaderField:@"Content-Length"];    
    [NSURLConnection connectionWithRequest:[request autorelease] delegate:self];

回答1:

I think it is because your Server set the post limit.Check the settings at your server side about the post data limit.



回答2:

When I rechecked this question, I think maybe I found what was the problem. When I do HTTP post, I usually don't set the content-length by myself. I just encode my post data as key=value&.. form and use the [NSMutableURLRequest setHTTPBody:data] method to add the data to the NSMutableURLRequest. I think it will do the rest for you include set the content-length for you. Even though I am not very familiar with HTTP protocol, but I think maybe the content-length represent the whole post data length, but here you set the content-length value with the length of key value data length.