NSURLSessionUploadTask failed to load file

Below is a snippet for loading an image file. I want to use only NSURLSessionUploadTask because it provides a background loading function that I want to use in my application.

I also want the POST parameter along with the file upload.

Also I am not good at server-side code. Someone please call me what am I doing wrong.

Download code

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"jpg"]; uint64_t bytesTotalForThisFile = [[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:NULL] fileSize]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:uploadPath]; [request setHTTPMethod:@"POST"]; [request setValue:[NSString stringWithFormat:@"%llu", bytesTotalForThisFile] forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"]; [request setTimeoutInterval:30]; NSString* filePath = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"jpg"]; NSURLSessionUploadTask *taskUpload= [self.uploadSession uploadTaskWithRequest:request fromFile:[[NSURL alloc] initFileURLWithPath:filePath]]; 

PHP code

 <?php $objFile = & $_FILES["file"]; $strPath = basename( $objFile["name"] ); if( move_uploaded_file( $objFile["tmp_name"], $strPath ) ) { print "The file " . $strPath . " has been uploaded."; } else { print "There was an error uploading the file, please try again!"; } 

On the server side, I get an empty array for $ _FILES

+7
php ios file-upload nsurlconnection nsurlsession
source share
2 answers

I will give an example code. Check if there are any errors on the console.

 // 1. config NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; // 2. if necessary set your Authorization HTTP (example api) // [config setHTTPAdditionalHeaders:@{@"<setYourKey>":<value>}]; // 3. Finally, you create the NSURLSession using the above configuration. NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; // 4. Set your Request URL NSURL *url = <yourURL>; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; // 5. Set your HTTPMethod POST or PUT [request setHTTPMethod:@"PUT"]; // 6. Encapsulate your file (supposse an image) UIImage *image = [UIImage imageNamed:@"imageName"]; NSData *imageData = UIImageJPEGRepresentation(image, 1.0); // 7. You could try use uploadTaskWithRequest fromData NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response; if (!error && httpResp.statusCode == 200) { // Uploaded } else { // alert for error saving / updating note NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode); } }]; 
0
source share

If this is complete code, you have not actually started the download. NSURLSession tasks do not start automatically (unlike some NSURLConnection calls). You must explicitly call their resume method to start the download, or the tasks will just sit there and do nothing.

Secondly, you really should use a URLForResource, not a path, and then convert it to a URL. This should not break your code, but it is much easier to use the URLs to get started.

Third, if you really need to use the path, convenient methods (fileURLWithPath :) are your friend.

Fourth, you do not need to set Content-Length and IIRC, you probably should not, because you do not know what the length of the content will be if the NSURLSession negotiates any encoding (for example, file data compression).

Fifth, if the file is large, 30 seconds may not be long enough.

Sixth, if you are running newer versions of iOS or OS X, make sure that you either use a properly configured HTTPS server or add a suitable exception for application security.

Finally, if you want to include other POST options, rather than just providing information about the data block as the request body, you will have to use a streaming request. Of course, you can use the GET parameters trivially, and this is what I would recommend you do, because it is a much simpler way to do something. :-)

0
source share

All Articles