iOS開發系列-文件上傳


概述

Http協議對文件上傳協議要求的
1. 必須設置請求頭Content-Type為multipart/form-data。在iOS中后面需要跟上分隔符比如:boundary=----WebKitFormBoundaryDYeXSvJz9Yuyf6Du。分割可以任意字符

2. 上傳的參數是有要求的,具體的數據格式如下

如果請求頭沒有設置Content-Type為multipart/form-data則為普通的POST請求。

文件上傳

通過NSURLConnection上傳文件

#define FMDataWithString(Str) [Str dataUsingEncoding:NSUTF8StringEncoding]
#define FMNewLine FMDataWithString(@"\r\n")

// #define FMSeparator @"----WebKitFormBoundaryt8fVxWuv0hn9uOjt" 分隔符

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    // 設置POST請求
    request.HTTPMethod = @"POST";
    // 上傳的請求頭必須參數設置
    [request setValue:@"multipart/form-data; boundary=----WebKitFormBoundaryt8fVxWuv0hn9uOjt" forHTTPHeaderField:@"Content-Type"];
    
    // 處理請求體
    request.HTTPBody = [self handleHttpBody];
    
    
    // 發送請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        NSLog(@"-------------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    }];
    
}

- (NSMutableData *)handleHttpBody
{
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"Snip20180325_5"], 1.0);
    
    NSMutableData *httpBodyData = [NSMutableData data];
    
    [httpBodyData appendData:FMDataWithString(@"------WebKitFormBoundaryt8fVxWuv0hn9uOjt")]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMDataWithString(@"Content-Disposition: form-data; name=\"file\"; filename=\"Snip20180325_11.png\"")]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMDataWithString(@"Content-Type: image/png")]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:imageData]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMNewLine];
    
    // 非文件參數
    [httpBodyData appendData:FMDataWithString(@"------WebKitFormBoundaryt8fVxWuv0hn9uOjt")]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMDataWithString(@"Content-Disposition: form-data; name=\"username\"")]; [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMNewLine];
    [httpBodyData appendData:FMDataWithString(@"tom")]; [httpBodyData appendData:FMNewLine];
    
    // 結束分隔符
    [httpBodyData appendData:FMDataWithString(@"------WebKitFormBoundaryt8fVxWuv0hn9uOjt--")];
    
    return httpBodyData;
}
@end

NSURLSession上傳文件

使用NSURLSession上傳文件跟NSURLConnection對比兩者步驟差不多,只是請求體的位置不一樣。NSURLConnection數據是放在request中。NSURLSession放在參數中;

NSURLSessionUploadTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:[self handleHttpBody] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"-------------%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];

AFNetworking文件上傳

NSDictionary *param = @{@"username": @"CoderHong"};
    [[AFHTTPSessionManager manager] POST:@"http://120.25.226.186:32812/upload" parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        /**
         設置需要上傳的文件
         @param name 服務器字段名
         @param fileName 要傳遞的文件名
         @param mimeType 文件的mimetype
         */
        [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"Snip20180325_5"], 1.0) name:@"file" fileName:@"Snip20180325_5.png" mimeType:@"image/png"];
        
        // 通過傳遞文件的路徑
        // [formData appendPartWithFileURL:[NSURL fileURLWithPath:@""] name:@"file" fileName:@"Snip20180325_5" mimeType:@"image/png" error:nil];
        // [formData appendPartWithFileURL:[NSURL fileURLWithPath:@""] name:@"file" error:nil];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"-----------%@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM