iOS 本地搭建服务器使用http传送(wifi快传)
2017-06-01 本文已影响528人
kenewang
1、使用第三方的框架:CocoaHTTPServer
下载地址:https://github.com/robbiehanson/CocoaHTTPServer
2、调用代码,我的百度网盘
链接: https://pan.baidu.com/s/1o8SDT26 密码:e53n
_httpserver = [[HTTPServer alloc] init];
[_httpserver setType:@"_http._tcp."];
[_httpserver setPort:16918];
NSString *webPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"website"];
[_httpserver setDocumentRoot:webPath];
[_httpserver setConnectionClass:[AYHTTPConnection class]];
[self startServer];
3、文件位置:
文件上传到沙盒里,自己可以定义路径。
- (void) processStartOfPartWithHeader:(MultipartMessageHeader *)header
{
MultipartMessageHeaderField *disposition = [header.fields objectForKey:@"Content-Disposition"];
NSString *fileName = [[disposition.params objectForKey:@"filename"] lastPathComponent];
if (fileName==nil || [fileName isEqualToString:@""])
return;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *uploadFolderPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"uploadFiles"];
NSString *uploadFilePath = [uploadFolderPath stringByAppendingPathComponent:fileName];
NSFileManager *fm = [NSFileManager defaultManager];
// 创建目录
if (![fm fileExistsAtPath:uploadFolderPath])
{
[fm createDirectoryAtPath:uploadFolderPath withIntermediateDirectories:YES attributes:nil error:nil];
}
//Ready to write the file, if the file already exists Overwrite
if (![fm createFileAtPath:uploadFilePath contents:nil attributes:nil])
{
return;
}
isUploading = YES;
storeFile = [NSFileHandle fileHandleForWritingAtPath:uploadFilePath];
NSDictionary *value = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithLongLong:uploadFileSize], @"totalfilesize", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:UPLOADSTART object:nil userInfo:value];
}
4、website文件(html)
本地代码调起的html路径,在第2步中有调用,这个是在pc端的web可以看到的界面
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>WiFi Transfer</title>
</head>
<body>
<h1>All Files</h1>
<p>%MyFiles%</p>
<form action="index.html" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<label>upload file:</label>
<input type="file" name="uploadnewfile" style="width:500px;">
<input type="submit" value="upload" class="black">
<style>
.black{color:#FFF;background-color:#333333;border-width:1px;}
</style>
</form>
</body>
</html>