NSURLSession上傳小文件

#import "ViewController.h"

#define     ZYXBoundary         @"520it"
#define     ZYXEncode(string)   [string dataUsingEncoding:NSUTF8StringEncoding]
#define     ZYXNewLine          [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]

@interface ViewController () 
/** session */
@property (nonatomic, strong) NSURLSession *session;
@end

@implementation ViewController

- (NSURLSession *)session{
    if (!_session) {
        NSURLSessionConfiguration *cfg = [NSURLSessionConfiguration defaultSessionConfiguration];
        cfg.timeoutIntervalForRequest = 10;
        // 是否允許使用蜂窩網(wǎng)絡(luò)(手機(jī)自帶網(wǎng)絡(luò))
        cfg.allowsCellularAccess = YES;
        _session = [NSURLSession sessionWithConfiguration:cfg];
    }
    return _session;
}

- (void)uploadFile{
    NSString *urlString = @"http://www.example.com:8080/upload";
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    requestM.HTTPMethod = @"POST";
    
    // 設(shè)置請(qǐng)求頭(告訴服務(wù)器,這是一個(gè)文件上傳的請(qǐng)求)
    [requestM setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", ZYXBoundary] forHTTPHeaderField:@"Content-Type"];
    
    // 設(shè)置請(qǐng)求體
    NSMutableData *body = [NSMutableData data];
    
    // 文件參數(shù)
    // 分割線
    [body appendData:ZYXEncode(@"--")];
    [body appendData:ZYXEncode(ZYXBoundary)];
    [body appendData:ZYXNewLine];
    
    // 文件參數(shù)名
    [body appendData:ZYXEncode([NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"test.png\""])];
    [body appendData:ZYXNewLine];
    
    // 文件的類型
    [body appendData:ZYXEncode([NSString stringWithFormat:@"Content-Type: image/png"])];
    [body appendData:ZYXNewLine];
    
    // 文件數(shù)據(jù)
    [body appendData:ZYXNewLine];
    [body appendData:[NSData dataWithContentsOfFile:@"/Users/zhaoyingxin/Desktop/test.png"]];
    [body appendData:ZYXNewLine];
    
    // 結(jié)束標(biāo)記
    /*
     --分割線--\r\n
     */
    [body appendData:ZYXEncode(@"--")];
    [body appendData:ZYXEncode(ZYXBoundary)];
    [body appendData:ZYXEncode(@"--")];
    [body appendData:ZYXNewLine];
    
    [[self.session uploadTaskWithRequest:requestM
                                fromData:body
                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                           NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
                       }]
     resume];
}

//{success : 上傳成功}
//{error : 上傳失敗}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容