#define XLBoundary @"XL"
#define XLLine @"\r\n"
#define XLEncode(string) [string dataUsingEncoding:NSUTF8StringEncoding]
// 1.请求服务器地址
NSURL *serverURL = [NSURL URLWithString:@""];
// 2.创建一个POST请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:serverURL];
request.HTTPMethod = @"POST";
// 3.设置请求体
NSMutableData *body = [NSMutableData data];
// 设置文件的其他参数
NSDictionary *params = @{@"":@""};
// 文件参数
// 分界线
[body appendData:XLEncode(@"--")];
[body appendData:XLEncode(XLBoundary)];
// 换行
[body appendData:XLEncode(XLLine)];
// 获取本地文件的地址, 同时转换成URL编码 文件的名字 文件的后缀名
NSURL *urlPath = [[NSBundle mainBundle] URLForResource:@"" withExtension:@""];
// 创建请求
NSURLRequest *requestPath = [NSURLRequest requestWithURL:urlPath];
// 发送请求
NSURLResponse *response = nil;
// 通过发送本地文件路径获取 MIMEType
[NSURLConnection sendSynchronousRequest:requestPath returningResponse:&response error:nil];
NSString *mimeType = response.MIMEType;
// 声明上传文件的格式
NSString *type = [NSString stringWithFormat:@"Content-Type:%@", mimeType];
[body appendData:XLEncode(type)];
// 换行
[body appendData:XLEncode(XLLine)];
// 将本地文件路径转换为data数据类型
NSData *fileData = [NSData dataWithContentsOfURL:urlPath];
[body appendData:XLEncode(XLLine)];
[body appendData:fileData];
[body appendData:XLEncode(XLLine)];
// 要上传的文件名
NSString *fileName = @"";
// 添加字段名称
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition:form-data; name=\"file\"; filename\"%@\"", fileName];
[body appendData:XLEncode(disposition)];
[body appendData:XLEncode(XLLine)];
// 非文件参数
[params enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[body appendData:XLEncode(@"--")];
[body appendData:XLEncode(XLBoundary)];
[body appendData:XLEncode(XLLine)];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition:form-data; name=\"%@\"", key];
[body appendData:XLEncode(disposition)];
[body appendData:XLEncode(XLLine)];
[body appendData:XLEncode(XLLine)];
[body appendData:XLEncode([obj description])];
[body appendData:XLEncode(XLLine)];
}];
// 结束标记
[body appendData:XLEncode(@"--")];
[body appendData:XLEncode(XLBoundary)];
[body appendData:XLEncode(@"--")];
[body appendData:XLEncode(XLLine)];
// 设置HTTPBody
request.HTTPBody = body;
// 4.设置请求头(告诉服务器这次传的诗歌文件数据, 同时是一个上传的请求)
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", XLBoundary];
[request setValue:contentType forHTTPHeaderField:@"Content-type"];
// 5.发送请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
}];
iOS开发之文件上传
最新推荐文章于 2023-10-24 21:10:19 发布