利用put上傳檔案到伺服器

來源:互聯網
上載者:User

#import "KUViewController.h"

#import "KUProgress.h"

@interfaceKUViewController ()<NSURLSessionTaskDelegate>

//下載進度的類,繼承UIview

@property (weak, nonatomic) IBOutlet  KUProgress *progressView;

 

@end

 

@implementation KUViewController

 

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    [self putFile];

}

 

/**

 *  用PUT方法上傳檔案,不經過瀏覽器傳遞

 */

-(void)putFile

{

   //1,url(協議+主機名稱+路徑+儲存到伺服器的檔案名稱)

     // post:url  (協議+主機名稱+上傳的伺服器的程式)

    NSString *urlStr = @"http://localhost/uploads/046.Post提交使用者隱私資料&MD5加密.mp4";

      //1.1編碼格式

    urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSURL *url = [NSURL URLWithString:urlStr];

    

    //2,request 請求(預設是get)

    NSMutableURLRequest *request = [NSMutableURLRequestrequestWithURL:url];

      //1>httpMethod

    request.HTTPMethod = @"PUT";

      //2>網路請求授權

    /**

        BASE64目前在網路上最流行的一種編碼方式,可以將二進位的資料轉換成字串,對方接受到之後,可以再講字串轉換成二進位檔案

        BASE64可以編碼,也可以解碼

     

      授權格式:

      (1)授權字串格式:使用者名稱:口令

      (2)授權模式:Basic Base64編碼的授權字串

      (3)位HTTPHEADERField的Authorization賦值

     

     */

    NSString *authStr = @"admin:admin";

    //將字串轉換成 Base64

     authStr = [self authBase64:authStr];

    //轉換成第二部的

    NSString *authBase64 = [NSString stringWithFormat:@"Basic %@",authStr];

    //轉換成第三部

    [request setValue:authBase64 forHTTPHeaderField:@"Authorization"];

    

    //3,session

      //1>.建立會話機制

    NSURLSessionConfiguration *config = [NSURLSessionConfigurationdefaultSessionConfiguration];

  NSURLSession *session =  [NSURLSessionsessionWithConfiguration:config delegate:selfdelegateQueue:[[NSOperationQueuealloc] init]];

    

    //2> 上傳任務

    //上傳的檔案的路徑

    NSURL *fileUrl =   [[NSBundle mainBundle] URLForResource:@"01.Post提交使用者隱私資料&MD5加密.mp4" withExtension:nil];

    [[session uploadTaskWithRequest:request fromFile:fileUrl] resume];

    

//   這是不用下載進度條的方法。 

//    NSURLSessionUploadTask *task = [session uploadTaskWithRequest:request fromFile:fileUrl completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

//        

//        //把位元據轉換成字串

//      NSString *str =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

//        NSLog(@"str = %@",str);

//    }];

//

    

}

 

#pragma mark -- 代理方法

 

-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend

{

    CGFloat value = (CGFloat)totalBytesSent / totalBytesExpectedToSend;

   // [NSThread sleepForTimeInterval:0.2];

    [[NSOperationQueuemainQueue] addOperationWithBlock:^{

         self.progressView.progress = value;

    }];

   

    NSLog(@"下載進度;value = %.03lf",value);

}

 

-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error

{

    NSLog(@"上傳失敗");

}

//轉換成Base64編碼授權字串

-(NSString *)authBase64:(NSString *)authStr

{

    

    //將字串轉換成位元局

    NSData *data = [authStr dataUsingEncoding:NSUTF8StringEncoding];

    return [data base64EncodedStringWithOptions:0];

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.