Uploading a file with POST using AFNetworking

2019-07-29 05:15发布

So I'm trying to upload an XML file to a server with POST using AFNetworking.
So using example code from their site I have this set up. When it runs, something is uploaded to the server (or at least it leaves my computer). I can monitor the upload, when the upload is finished, the server recognizes that it completed and goes to load the file, but it loads an old XML. So its connecting properly to the server, but I'm not sure why the file upload isn’t working correctly. Also I just want to send the file, the server doesn’t need any headers or parameters etc.
So I'm wondering if I’ve stored the data correctly? Or if I'm not sending it the server properly or what? Any suggestions would be helpful

NSData *iTunesXMLData = [NSData dataWithContentsOfFile:filePath];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

  /* NSMutableURLRequest *request =[httpClientmultipartFormRequestWithMethod:@"POST"     
path:@"/upload.php?id=5" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData:iTunesXMLData name:@"iTunes Music Library" fileName:@"iTunes Music Library.xml" mimeType:@"application/xml"];
}];*/

//I tried this way also, both did the same thing

NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload.php?id=5" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFormData:iTunesXMLData name:@"iTunes Music Library"];
}];`

 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];`

NSLog(@"Operation: %@", operation);
[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
    NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation start];

1条回答
Fickle 薄情
2楼-- · 2019-07-29 05:39

Have you tried to catch the success/failure of the operation? Try this after setUploadProgressBlock:

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Operation ended successfully
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Something happened! 
    NSLog(@"ERROR: %@, %@", operation, error);
    // Here you can catch operation.responseString to see the response of your server
}];

This is an easy way to know what your server returned. If something uploads to your server, double check that you're getting the right file. AFAIK, your AFNetwork seems ok.

查看更多
登录 后发表回答