其他分享
首页 > 其他分享> > IOS开发基础之单文件上传基础最原始的方式

IOS开发基础之单文件上传基础最原始的方式

作者:互联网

IOS开发基础之单文件上传基础最原始的方式

在这里插入图片描述

在这里插入图片描述

info.plist 加入一行代码

<key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
     <true/>
    </dict>

在这里插入图片描述

//
//  ViewController.m
//  05-上传单个文件
//
//  Created by 鲁军 on 2021/2/13.
//

#import "ViewController.h"
#define kBOUNDARY @"abc"
@interface ViewController ()

@end

@implementation ViewController

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

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    //@"http://localhost:8080/MJServer/upload"
   // [self uploadFile];
    NSString *path=[[NSBundle mainBundle] pathForResource:@"IOSThreadNetwork.zip" ofType:nil];
    [self uploadFile:@"http://localhost:8080/MJServer/upload" fieldName:@"file" filePath:path];
}


-(void)uploadFile:(NSString *)urlString fieldName:(NSString *)fieldName
         filePath:(NSString *)filePath{
    
    NSURL *url  =[NSURL URLWithString:urlString];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"post";
    [request setValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",kBOUNDARY] forHTTPHeaderField:@"Content-Type"];
   
    //request.HTTPBody=[self makeBody];
    request.HTTPBody=[self makeBody:fieldName filePath:filePath];
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(connectionError){
            NSLog(@"连接错误 %@",connectionError);
            return;
        }
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if(httpResponse.statusCode==200||httpResponse.statusCode==304){
            //解析数据
            id json =[NSJSONSerialization JSONObjectWithData:data options:nil error:NULL];
            NSLog(@"%@",json);
            
        }else{
            NSLog(@"服务器内部错误");
        }
        
    }];
    
    
    
}


-(void)uploadFile1{
    
    NSURL *url  =[NSURL URLWithString:@"http://localhost:8080/MJServer/upload"];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"post";
    [request setValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",kBOUNDARY] forHTTPHeaderField:@"Content-Type"];
    
    request.HTTPBody=[self makeBody];
    
   
    
    
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(connectionError){
            NSLog(@"连接错误 %@",connectionError);
            return;
        }
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        if(httpResponse.statusCode==200||httpResponse.statusCode==304){
            //解析数据
            id json =[NSJSONSerialization JSONObjectWithData:data options:nil error:NULL];
            NSLog(@"%@",json);
            
        }else{
            NSLog(@"服务器内部错误");
        }
        
    }];
    
    
    
}


-(NSData *)makeBody:(NSString *)fieldName
            filePath:(NSString *)filePath{
    NSMutableData *mData=[NSMutableData data];
    NSMutableString *mString=[NSMutableString string];
    [mString appendFormat:@"--%@\r\n",kBOUNDARY];
    [mString appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",fieldName,[filePath lastPathComponent]];
    [mString appendString:@"Content-Type: application/octet-stream\r\n"];
    [mString appendString:@"\r\n"];
    
    [mData appendData:[mString dataUsingEncoding:NSUTF8StringEncoding]];
    
    //第二部分
    // 加载文件
   // NSString *path =[[NSBundle mainBundle] pathForResource:@"07.jpg" ofType:nil];
    NSData *data =[NSData dataWithContentsOfFile:filePath];
    
    [mData appendData:data];
    
    
    NSString *end=[NSString stringWithFormat:@"\r\n--%@--",kBOUNDARY];
    [mData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
   
    return  mData.copy;
    
}


-(NSData *)makeBody{
    NSMutableData *mData=[NSMutableData data];
    NSMutableString *mString=[NSMutableString string];
    [mString appendFormat:@"--%@\r\n",kBOUNDARY];
    [mString appendString:@"Content-Disposition: form-data; name=\"file\"; filename=\"07.jpg\"\r\n"];
    [mString appendString:@"Content-Type: image/jpeg\r\n"];
    [mString appendString:@"\r\n"];
    
    [mData appendData:[mString dataUsingEncoding:NSUTF8StringEncoding]];
    
    //第二部分
    // 加载文件
    NSString *path =[[NSBundle mainBundle] pathForResource:@"07.jpg" ofType:nil];
    NSData *data =[NSData dataWithContentsOfFile:path];
    
    [mData appendData:data];
    
    
    NSString *end=[NSString stringWithFormat:@"\r\n--%@--",kBOUNDARY];
    [mData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
   
    return  mData.copy;
    
}
@end

标签:mData,mString,filePath,data,IOS,request,NSString,之单,上传
来源: https://blog.csdn.net/A1521315qwss/article/details/113800665