git地址:https://github.com/swisspol/GCDWebServer
或者用pod安装:pod "GCDWebServer/WebUploader", "~> 3.0"
#import "WebUploaderViewController.h"
#import "GCDWebUploader.h"
#import <AFNetworking/AFNetworking.h>
@interface WebUploaderViewController () <GCDWebUploaderDelegate>
@property (nonatomic, strong) GCDWebUploader *webServer;
@property (nonatomic, strong) NSString *documentsPath;
@property (nonatomic, strong) UILabel *networkLabel;
@end
@implementation WebUploaderViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self createCustomNavi:@"WebUploader"];
[self setUp];
}
- (void)setUp {
//创建webServer,设置根目录
[self creatDir:self.documentsPath];
_webServer = [[GCDWebUploader alloc] initWithUploadDirectory:self.documentsPath];
//设置代理
_webServer.delegate = self;
_webServer.allowHiddenItems = YES;
//限制文件上传类型
_webServer.allowedFileExtensions = @[@"mp3",@"doc", @"docx", @"xls", @"xlsx", @"txt", @"pdf"];
_networkLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, UI_SCREEN_WIDTH, 100)];
_networkLabel.textColor = [UIColor blackColor];
_networkLabel.textAlignment = 1;
_networkLabel.font = [UIFont systemFontOfSize:14];
[self.view addSubview:_networkLabel];
BOOL isOK = [_webServer start];
if (isOK) {
_networkLabel.text = [NSString stringWithFormat:@"%@", _webServer.serverURL];
}else {
_networkLabel.text = @"启动失败,请退出当前页面,重试";
}
}
/**
创建文件夹
@param dirPath 文件夹名称
@return 创建成功或失败
*/
- (BOOL)creatDir:(NSString *)dirPath {
if ([[NSFileManager defaultManager] fileExistsAtPath:dirPath]) {//判断dirPath路径文件夹是否已存在,此处dirPath为需要新建的文件夹的绝对路径
NSLog(@"沙盒目录已经存在%@",dirPath);
return NO;
}else {
[[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];//创建文件夹
NSLog(@"创建成功%@",dirPath);
return YES;
}
}
- (NSString *)documentsPath {
return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"Music"]];
}
#pragma mark - <GCDWebUploaderDelegate>
//上传文件到目录
- (void)webUploader:(GCDWebUploader*)uploader didUploadFileAtPath:(NSString*)path {
NSLog(@"上传音乐 %@", [self getMusicFileArray]);
}
- (NSString *)getFilePath:(NSString *)fileName {
return [self.documentsPath stringByAppendingPathComponent:fileName];
}
//获取目录下的文件
- (NSMutableArray *)getMusicFileArray {
NSFileManager *fileManager = [NSFileManager defaultManager];
return [NSMutableArray arrayWithArray:[fileManager contentsOfDirectoryAtPath:self.documentsPath error:nil]];
}
@end
在浏览器输入获取的ip(_webServer.serverURL)就可以上传文件到手机了,需要电脑和手机在同一网络