iOS网络 POST模拟表单上传单个与多个文件(直接调用分类里的方法即可)

本文介绍了一个iOS应用中实现文件上传的方法,包括单个文件和多个文件的上传过程。使用Objective-C语言通过NSURLConnection进行异步请求,展示了如何将图片文件打包并发送到服务器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  ViewController.m
//  01-POST上传文件
//
//  Created by 刘凡 on 15/2/8.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "ViewController.h"
#import "NSMutableURLRequest+Multipart.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self multiPostUpload];
}

// MARK: - 多个文件上传
- (void)multiPostUpload {
    NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload-m.php"];
    
    NSURL *fileUrl1 = [[NSBundle mainBundle] URLForResource:@"demo.jpg" withExtension:nil];
    NSData *data1 = [NSData dataWithContentsOfURL:fileUrl1];
    NSURL *fileURL2 = [[NSBundle mainBundle] URLForResource:@"001.png" withExtension:nil];
    NSData *data2 = [NSData dataWithContentsOfURL:fileURL2];
    NSArray *dataArray = @[data1, data2];
    NSArray *fileNames = @[@"demo.jpg", @"001.png"];
    
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileDataArray:dataArray fileNames:fileNames];
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileURLs:@[fileUrl1, fileURL2] fileNames:fileNames];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileURLs:@[fileUrl1, fileURL2]];
    
    // 3. connection
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
    }];
}

// MARK: - 单个文件上传
- (void)postUpload {
    // 1. url
    NSURL *url = [NSURL URLWithString:@"http://localhost/post/upload.php"];
    
    // 2. request
    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"demo.jpg" withExtension:nil];
    NSData *data = [NSData dataWithContentsOfURL:fileUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url keyName:@"userfile" fileData:data fileName:@"bcd.jpg"];
    
    // 3. connection
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL]);
    }];
}

@end

http://pan.baidu.com/s/1ntqTaWT

转载于:https://my.oschina.net/lanrenbar/blog/379290

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值