之前公司的Java工程师比较厉害,所以我在前端上传一个通过编码的NSString或者NSData类型的数据,就可以上传成功,现在因为此Java工程师没做过,所以为了实现类似于发布照片或小视频这样的功能,不得已将内容以表单的形式上传,实现发布的功能。
同时要记住,后台Java代码,其他的参数可以通过参数名获取值,资源内容可以直接通过MusultFile形式进行接收即可,这样就会直接生成一个资源文件,然后可以上传云端生成一个url地址,方便前端资源展示。
下面展示Demo中的代码:也会附上我实际应用的部分代码,具体大家自行研究,有问题请留言,不喜勿喷~
//请求方法
-(void)method4{
NSURL *uploadURL = [NSURL URLWithString:@"http://192.168.124.233/report/addReportTest"];
NSLog(@"请求路径为%@",uploadURL);//接口路径:根据自己的需要修改
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//body
NSData *body = [self prepareDataForUpload];
//request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
[request setValue:@"BBH" forHTTPHeaderField:@"User-Agent"];
[request setValue:@"max-age=7200" forHTTPHeaderField:@"Cache-Control"];
//设置上传数据的长度及格式
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary]forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)body.length]forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"message: %@", message);
[session invalidateAndCancel];
}];
[uploadTask resume];
});
}
//生成bodyData
-(NSData*) prepareDataForUpload
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *uploadFilePath = [documentsDirectory stringByAppendingPathComponent:fileName];
//NSLog(@"documen %@",uploadFilePath);
NSString *lastPathfileName = [uploadFilePath lastPathComponent];
NSMutableData *bodyData = [NSMutableData data];
NSData *dataOfFile = [[NSData alloc] initWithContentsOfFile:uploadFilePath];
NSDictionary *paramDic = @{@"userId":@"1234",@"content":@"哈哈",@"isPublic":@"0",@"fileType":@"0"};
[paramDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
NSString *boundry1 = [NSString stringWithFormat:@"--%@\r\n",boundary];
[bodyData appendData:[[NSString stringWithFormat:@"%@", boundry1] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",key];
NSLog(@"%@",disposition);
[bodyData appendData:[[NSString stringWithFormat:@"%@", disposition] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"%@", obj] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}];
if (dataOfFile) {
//连续上传相同的三张图片
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:dataOfFile];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:dataOfFile];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParam, lastPathfileName] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:dataOfFile];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
return bodyData;
}
我项目中实际修改的代码样式:
#pragma mark ---- 利用 web表单的形式 上传图片或小视频 参数一:url地址;参数二:0:照片,1:视频;参数三:媒体数组;参数四:其他参数字典集合
+(void)uploadWebFormWithUrlStr:(NSString *)urlStr mediaType:(NSString *)type mediaArray:(NSArray *)array param:(NSDictionary *)paramDic complete:(void(^)(id))complete
{
if ([self isConnectionAvailable]) {
NSURL *uploadURL = [NSURL URLWithString:urlStr];
//NSLog(@"请求路径为%@",uploadURL);
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//body
NSData *body = [self prepareDataForUploadWithArray:array param:paramDic mediaType:type];
//request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:uploadURL];
[request setValue:@"BBH" forHTTPHeaderField:@"User-Agent"];
[request setValue:@"max-age=7200" forHTTPHeaderField:@"Cache-Control"];
//设置上传数据的长度及格式
[request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",WEB_BOUNDARY]forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%lu",(unsigned long)body.length]forHTTPHeaderField:@"Content-Length"];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:body];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:body completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
//NSLog(@"message: %@", resultDic);
complete(resultDic);
}];
//[session invalidateAndCancel];
[uploadTask resume];
});
}else{
//complete(nil);
[SVProgressHUD showErrorWithStatus:@"无网络/网络不可用"];
}
}
//生成bodyData
+(NSData*) prepareDataForUploadWithArray:(NSArray *)array param:(NSDictionary *)paramDic mediaType:(NSString *)type
{
NSMutableData *bodyData = [NSMutableData data];
//其他参数字典集合
[paramDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL *_Nonnull stop) {
NSString *boundry1 = [NSString stringWithFormat:@"--%@\r\n",WEB_BOUNDARY];
[bodyData appendData:[[NSString stringWithFormat:@"%@", boundry1] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n",key];
//NSLog(@"%@",disposition);
[bodyData appendData:[[NSString stringWithFormat:@"%@", disposition] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"%@", obj] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}];
//媒体添加
for (ACMediaModel *acMediaM in array) {
NSData *dataOfFile = [[NSData alloc] initWithData:acMediaM.uploadType];
if (dataOfFile) {
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", WEB_FILEPARAM, acMediaM.name] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:dataOfFile];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
if ([type isEqualToString:@"1"]) {
//添加视频图片
NSData *imgOfFile = UIImageJPEGRepresentation(acMediaM.image, 0.5);
[bodyData appendData:[[NSString stringWithFormat:@"--%@\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", WEB_FILEPARAM, @"video.png"] dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:[@"Content-Type: application/zip\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[bodyData appendData:imgOfFile];
[bodyData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
}
}
[bodyData appendData:[[NSString stringWithFormat:@"--%@--\r\n", WEB_BOUNDARY] dataUsingEncoding:NSUTF8StringEncoding]];
return bodyData;
}
源码下载:https://github.com/hbblzjy/iOSuploadFileWithWebForm