iOS 上傳文件


#define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]


-(void) uploadWithUrlStr:(NSString*)url images:(NSDictionary*) images withCardImage:(UIImage*) cardImage  parmas:(NSDictionary *)params
{
    // 文件上傳
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";

    // 設置請求體
    NSMutableData *body = [NSMutableData data];

    /***************文件參數***************/
    [images enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        // 參數開始的標誌

        [body appendData:YYEncode(@"--YY\r\n")]; NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", key, key]; [body appendData:YYEncode(disposition)]; NSString *type = [NSString stringWithFormat:@"Content-Type: %@\r\n", @"image/jpeg"]; [body appendData:YYEncode(type)]; [body appendData:YYEncode(@"\r\n")]; [body appendData:obj]; [body appendData:YYEncode(@"\r\n")];
    }];
    /***************普通參數***************/
    [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { // 參數開始的標誌
        [body appendData:YYEncode(@"--YY\r\n")];
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", key]; [body appendData:YYEncode(disposition)];
        [body appendData:YYEncode(@"\r\n")];
        [body appendData:YYEncode(obj)];
        [body appendData:YYEncode(@"\r\n")]; }];
    /***************參數結束***************/ // YY--\r\n
    [body appendData:YYEncode(@"--YY--\r\n")];
    request.HTTPBody = body; // 設置請求頭
    // 請求體的長度
    [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    // 聲明這個POST請求是個文件上傳
    [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
    // 發送請求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSLog(@"%@", dict);
        } else {
            NSLog(@"上傳失敗");
        }
    }];
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章