zoukankan      html  css  js  c++  java
  • iOS开发网络篇—文件的上传

    iOS开发网络篇—文件的上传

    说明:文件上传使用的时POST请求,通常把要上传的数据保存在请求体中。本文介绍如何不借助第三方框架实现iOS开发中得文件上传。

      由于过程较为复杂,因此本文只贴出部分关键代码。

    主控制器的关键代码:

    YYViewController.m

    复制代码
     1 #import "YYViewController.h"
     2 
     3 #define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
     4 
     5 @interface YYViewController ()
     6 
     7 @end
     8 
     9 @implementation YYViewController
    10 
    11 - (void)viewDidLoad
    12 {
    13     [super viewDidLoad];
    14     // Do any additional setup after loading the view, typically from a nib.
    15 }
    16 
    17 - (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
    18 {
    19     // 文件上传
    20     NSURL *url = [NSURL URLWithString:@"http://192.168.1.200:8080/YYServer/upload"];
    21     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    22     request.HTTPMethod = @"POST";
    23     
    24     // 设置请求体
    25     NSMutableData *body = [NSMutableData data];
    26     
    27     /***************文件参数***************/
    28     // 参数开始的标志
    29     [body appendData:YYEncode(@"--YY
    ")];
    30     // name : 指定参数名(必须跟服务器端保持一致)
    31     // filename : 文件名
    32     NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"
    ", name, filename];
    33     [body appendData:YYEncode(disposition)];
    34     NSString *type = [NSString stringWithFormat:@"Content-Type: %@
    ", mimeType];
    35     [body appendData:YYEncode(type)];
    36     
    37     [body appendData:YYEncode(@"
    ")];
    38     [body appendData:data];
    39     [body appendData:YYEncode(@"
    ")];
    40     
    41     /***************普通参数***************/
    42     [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    43         // 参数开始的标志
    44         [body appendData:YYEncode(@"--YY
    ")];
    45         NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"
    ", key];
    46         [body appendData:YYEncode(disposition)];
    47 
    48         [body appendData:YYEncode(@"
    ")];
    49         [body appendData:YYEncode(obj)];
    50         [body appendData:YYEncode(@"
    ")];
    51     }];
    52     
    53     /***************参数结束***************/
    54     // YY--
    
    55     [body appendData:YYEncode(@"--YY--
    ")];
    56     request.HTTPBody = body;
    57     
    58     // 设置请求头
    59     // 请求体的长度
    60     [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
    61     // 声明这个POST请求是个文件上传
    62     [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
    63     
    64     // 发送请求
    65     [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    66         if (data) {
    67             NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    68             NSLog(@"%@", dict);
    69         } else {
    70             NSLog(@"上传失败");
    71         }
    72     }];
    73 }
    74 
    75 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    76 {
    77     // Socket 实现断点上传
    78     
    79     //apache-tomcat-6.0.41/conf/web.xml 查找 文件的 mimeType
    80 //    UIImage *image = [UIImage imageNamed:@"test"];
    81 //    NSData *filedata = UIImagePNGRepresentation(image);
    82 //    [self upload:@"file" filename:@"test.png" mimeType:@"image/png" data:filedata parmas:@{@"username" : @"123"}];
    83     
    84     // 给本地文件发送一个请求
    85     NSURL *fileurl = [[NSBundle mainBundle] URLForResource:@"itcast.txt" withExtension:nil];
    86     NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
    87     NSURLResponse *repsonse = nil;
    88     NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&repsonse error:nil];
    89     
    90     // 得到mimeType
    91     NSLog(@"%@", repsonse.MIMEType);
    92     [self upload:@"file" filename:@"itcast.txt" mimeType:repsonse.MIMEType data:data parmas:@{
    93                                                                                               @"username" : @"999",
    94                                                                                               @"type" : @"XML"}];
    95 }
    96 
    97 @end
    复制代码

    补充说明:

    文件上传请求数据格式

    部分文件的MIMEType

     
     
  • 相关阅读:
    Android 针对单个Activity设置状态栏颜色
    Android Studio 无法预览xml布局视图:failed to load AppCompat ActionBar with unkNown error
    浅谈EditText控件的inputType类型
    Android项目实战(四十三):夜神模拟器
    浅谈SnackBar(Toast大兄弟)
    打包错误--Error:A problem was found with the configuration of task ':app:packageRelease'.
    Android项目实战(四十二):启动页优化,去除短暂白屏或黑屏
    Android项目实战(四十一):游戏和视频类型应用 状态栏沉浸式效果
    04-01 集成学习基础
    02-24 决策树总结
  • 原文地址:https://www.cnblogs.com/187n/p/5060914.html
Copyright © 2011-2022 走看看