如何从互联网下载docx,pdf,图像,pptx或任何文件 [英] How to download docx , pdf , image , pptx , or any file from a internet

查看:186
本文介绍了如何从互联网下载docx,pdf,图像,pptx或任何文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从要求提供身份验证凭据的站点下载docx,pdf,image,pptx或任何文件我尝试传递凭据并且nsdata中的数据仍然是其他内容,但它存储了保留本地创建的文件可以任何人都可以帮助代码下载任何类型的文件。

How to download docx , pdf , image , pptx , or any file from a site which ask for credentials for authentication i tried passing the credentials and still data in the nsdata is something else but it store that detain the file created locally can anybody help in the code for downloading any kind of file.

代码如下:
in this buttonClicked从其他文件调用
DownloadingFile .h

the code is as follows: in this buttonClicked is called from other file DownloadingFile.h

    #import "MyAppDelegate.h"

@interface DownloadingFile : NSObject
{
    NSMutableData *webData;
    NSMutableString *soapResults;
    NSURLConnection *conn;
    BOOL *elementFound; 
    BOOL isDoneParsing;
    MyAppDelegate *mydelegate;

    NSString *userCd,*passWord,*siteUrl;

}
@property (nonatomic ,retain) MyAppDelegate *mydelegate;
-(void)buttonClicked;
-(bool)getIsDone;
@end

DownloadingFile.m

DownloadingFile.m

#import "DownloadingFile.h"
#import "iExploreAppDelegate.h"

@implementation DownloadingFile

@synthesize mydelegate;

- (void)buttonClicked
{
    mydelegate=(MyAppDelegate *)[[UIApplication sharedApplication] delegate];

    userCd=[[NSString alloc] initWithString:[mydelegate getUserId]];
    passWord=[[NSString alloc] initWithString:[mydelegate getPassword]];

    NSLog(@"In Downloading; ");

    NSURL *url =[NSURL URLWithString:[@"http://abcdef.xyz.com/Docs/NewFolder/myFile.docx" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
        [req setValue:[NSString stringWithFormat:@"bytes=%ld-",0] forHTTPHeaderField:@"Range"];
        [req addValue: @"docx" forHTTPHeaderField:@"Content-Type"];
        [req setHTTPMethod:@"POST"];

      //---set the headers---
   conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

    if (conn) {
        NSLog(@"connection done ");

       webData = [[NSMutableData data] init];
    }   
} 


-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential;

      newCredential=[NSURLCredential credentialWithUser:userCd password:passWord persistence:NSURLCredentialPersistenceNone];
      NSLog(@"Crediantials done ");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        NSError* error = [NSError errorWithDomain:@"SoapRequest" code:403 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: @"Could not authenticate this request", NSLocalizedDescriptionKey,nil]];
        NSLog(@"Credentials are not valid");
        [mydelegate loginFailled:false];
    }
}



-(void) connection:(NSURLConnection *) connection 
didReceiveResponse:(NSURLResponse *) response {
    //[webData setLength: 0];
}

-(void) connection:(NSURLConnection *) connection 
    didReceiveData:(NSData *) data {
    NSLog(@"recevied data %@",data);
    webData=[NSMutableData dataWithData:data];
    [webData appendData:data];
}

-(void) connection:(NSURLConnection *) connection 
  didFailWithError:(NSError *) error {
    [webData release];
    [connection release];
}
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {

    NSLog(@"Did Finish Loading done ");

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *documentsDirectory = [paths objectAtIndex:0];

    NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:@"FileName.docx"];

    [webData writeToFile:pdfPath atomically:YES];

    [connection release];

}


推荐答案

我只是写了一个快速的应用程序,使用Apple的 NSURLConnection 进行测试,这是一个简单而强大的解决方案。我下载了几百KB的Word和PowerPoint文件。对于身份验证,我使用.htaccess。奇迹般有效。这是相关的代码。

I just wrote a quick app to test using Apple's NSURLConnection which is both a simple and robust solution. I downloaded a few hundred KB Word and PowerPoint files. For authentication I used .htaccess. Works like a charm. Here is the relevant code.

- (IBAction)clickedDownload:(id)sender {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://myserver.com/downloadTest/testfile.pptx"]];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
    [connection start];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   // inform the user
}

-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {        
        NSURLCredential *newCredential;
        newCredential = [NSURLCredential credentialWithUser:@"theUsername"
                                                   password:@"thePassword"
                                                persistence:NSURLCredentialPersistenceNone];
        [[challenge sender] useCredential:newCredential
               forAuthenticationChallenge:challenge];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        // inform the user that password is incorrect
    }
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    receivedData = [[NSMutableData alloc] init];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [receivedData appendData:data]; 
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSURL *docDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    NSURL *filePath = [docDirectory URLByAppendingPathComponent:@"testfile.pptx"];
    [receivedData writeToURL:filePath atomically:YES];
    [receivedData release];
    connection = nil;
}

现在我打开〜/ Library / Application Support /中的文件iPhone模拟器/ 4.3.2 /应用程序/ [独特应用程序代码] /文档 - 效果很好!

Now I opened the files in ~/Library/Application Support/iPhone Simulator/4.3.2/Applications/[unique-application-code]/Documents- works great!

这篇关于如何从互联网下载docx,pdf,图像,pptx或任何文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆