zoukankan      html  css  js  c++  java
  • 上传文件至服务器(图片)

    要求:

    //
    //  FileSelectedViewController.h
    //  移动办公
    //
    //  Created by 张艳锋 on 2018/10/25.
    //  Copyright © 2018年 dev. All rights reserved.
    //
    
    #import <UIKit/UIKit.h>
    
    
    @interface FileSelectedViewController : UIViewController
    
    @end
    //
    //  FileSelectedViewController.m
    //  移动办公
    //
    //  Created by 张艳锋 on 2018/10/25.
    //  Copyright © 2018年 dev. All rights reserved.
    //
    
    #import "FileSelectedViewController.h"
    
    #define YYEncode(str) [str dataUsingEncoding:NSUTF8StringEncoding]
    
    @interface FileSelectedViewController ()<UITableViewDelegate,UITableViewDataSource,PullListTableDelegate>
    
    @property(nonatomic,strong)PullListTableView *tableView;
    
    @property(nonatomic,strong)UIView *blankView;
    @property(nonatomic,strong)NSMutableArray *nameMutArray;
    @property(nonatomic,strong)NSDictionary *fileDic;
    @property(nonatomic,strong)NSString *selectedFile;
    
    @end
    
    @implementation FileSelectedViewController
    -(NSString *)selectedFile{
        if (!_selectedFile) {
            _selectedFile = [[NSString alloc]init];
        }
        return _selectedFile;
    }
    -(NSMutableArray *)nameMutArray{
        if (!_nameMutArray) {
            _nameMutArray = [[NSMutableArray alloc]init];
        }
        return _nameMutArray;
    }
    -(NSDictionary *)fileDic{
        if (!_fileDic) {
            _fileDic = [[NSDictionary alloc]init];
        }
        return _fileDic;
    }
    
    -(UIView *)blankView
    {
        if(!_blankView)
        {
            _blankView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH, [UIScreen mainScreen].bounds.size.height - SafeAreaTopHeight)];
            _blankView.backgroundColor = [UIColor colorWithRed:(CGFloat)241 / 255 green:(CGFloat)241 / 255 blue:(CGFloat)241 / 255 alpha:1.0];
            UIImage *image = [UIImage imageNamed:@"blank_page"];
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH * 0.4, JX_SCREEN_WIDTH * 0.4)];
            imageView.center = CGPointMake(_blankView.center.x, _blankView.center.y - 88);
            imageView.image = image;
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y + imageView.frame.size.height + 10, imageView.frame.size.width, 18.0)];
            label.textColor = [UIColor colorWithRed:(CGFloat)124 / 255 green:(CGFloat)124 / 255 blue:(CGFloat)124 / 255 alpha:1.0];
            label.font = [UIFont systemFontOfSize:16];
            label.text = @"暂无内容";
            label.textAlignment = NSTextAlignmentCenter;
            [_blankView addSubview:imageView];
            [_blankView addSubview:label];
        }
        return  _blankView;
    }
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self addTopNaviBarWithTitle:@"上传文件"];
        
        self.fileDic = [self localFile];
        self.nameMutArray =[[NSMutableArray alloc]initWithArray:[_fileDic allKeys]];
        
        self.tableView = [[PullListTableView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - SafeAreaTopHeight- SafeAreaBottomHeight)];
        self.tableView.delegate = self;
        self.tableView.dataSource = self;
        self.tableView.pullListDelegate = self;
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.tableFooterView = [UIView new];
        [self.view addSubview:self.tableView];
    
    }
    
    #pragma mark----导航栏
    -(void)addTopNaviBarWithTitle:(NSString *)title
    {
        UIView *naviBar = [[UIView alloc]initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH, SafeAreaTopHeight)];
        UIColor *naviColor = NAVIBAR_COLOR_DEFAULT;
        naviBar.backgroundColor = naviColor;
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, JX_SCREEN_WIDTH-40-40, 132.0 / SCALE)];
        titleLabel.font = TITLE_FONT_SIZE;
        titleLabel.textColor = [UIColor whiteColor];
        titleLabel.textAlignment =  IFLY_ALIGN_CENTER;
        [titleLabel setCenter:CGPointMake(naviBar.center.x, naviBar.center.y + SCREEN_Y / 2.0)];
        [naviBar addSubview:titleLabel];
        titleLabel.hidden = NO;
        titleLabel.text = title;
     
        UIButton *backBottomBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, SCREEN_Y, 60, 44)];
        backBottomBtn.backgroundColor = [UIColor clearColor];
        [backBottomBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        [naviBar addSubview:backBottomBtn];
        UIButton *backButton = [[UIButton alloc]initWithFrame:CGRectMake(36.0 / SCALE,SCREEN_Y+ (44-66.0 / SCALE)/2, 66.0 / SCALE, 66.0 / SCALE)];
        [backButton setImage:[UIImage imageNamed:@"Right"] forState:UIControlStateNormal];
        [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
        [naviBar addSubview:backButton];
        [self.view addSubview:naviBar];
    }
    -(void)goBack
    {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
    
    
    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        CGFloat subH = 40.0;
        
        return subH;
    }
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    {
        return 1;
    }
    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    {
        return self.nameMutArray.count;
    }
    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        UITableViewCell *cell = [[UITableViewCell alloc]init];
        cell.textLabel.text = [self.nameMutArray objectAtIndex:indexPath.row];
        return cell;
    }
    -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        
        self.selectedFile = [self.nameMutArray objectAtIndex:indexPath.row];
        
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"上传文件" message:self.selectedFile delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
    }
    
    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0){
        
        if (buttonIndex == 1) {
            // 给本地文件发送一个请求
            
            NSData *data = [NSData dataWithContentsOfFile:[_fileDic objectForKey:_selectedFile]];
            NSDictionary *parms=@{@"***" : @"180725205942u******nTt5sg7ReWmV",@"***" : @"18072520594*******sg7ReWmV",@"****" : @"1",@"fileId": @""};
            //上传文件
            [self upload:@"file" filename:self.selectedFile mimeType:nil data:data parmas:parms];
            
        }
    }
    
    - (void)upload:(NSString *)name filename:(NSString *)filename mimeType:(NSString *)mimeType data:(NSData *)data parmas:(NSDictionary *)params
    {
        //获取文件的后缀名
        NSString *extension = [filename componentsSeparatedByString:@"."].lastObject;
        //设置mimeType
        if ([filename hasSuffix:@"png"]||[filename  hasSuffix:@"jpg"]||[filename hasSuffix:@"jpeg"]||[filename hasSuffix:@"bmp"]) {
            mimeType = [NSString stringWithFormat:@"image/%@", extension];
        } else if([filename hasSuffix:@"mp3"]){
            mimeType = [NSString stringWithFormat:@"audio/mpeg"];
        }else if([filename hasSuffix:@"mp4"]||[filename hasSuffix:@"mov"]||[filename hasSuffix:@"mpg4"]){
            mimeType = [NSString stringWithFormat:@"video/mp4"];
        }else if([filename hasSuffix:@"js"]){
            mimeType = [NSString stringWithFormat:@"application/javascript"];
        }else if([filename hasSuffix:@"pdf"]){
            mimeType = [NSString stringWithFormat:@"application/pdf"];
        }else if([filename hasSuffix:@"text"]||[filename hasSuffix:@"txt"]){
            mimeType = [NSString stringWithFormat:@"text/plain"];
        }else if([filename hasSuffix:@"json"]){
            mimeType = [NSString stringWithFormat:@"application/json"];
        }else if([filename hasSuffix:@"xml"]){
            mimeType = [NSString stringWithFormat:@"text/xml"];
        }else{
            mimeType = [NSString stringWithFormat:@"text/plain"];
        }
        
        // 文件上传
        NSString *url =[NSString stringWithFormat:@"%@/%@/**/****************/********",BASEURL,PLATFORM];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:30];
        request.HTTPMethod = @"POST";
        
        // 设置请求体
        NSMutableData *body = [NSMutableData data];
        
        /***************文件参数***************/
        // 参数开始的标志
        [body appendData:YYEncode(@"--YY
    ")];
        // name : 指定参数名(必须跟服务器端保持一致)
        // filename : 文件名
        NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"; filename="%@"
    ", name, filename];
        [body appendData:YYEncode(disposition)];
        NSString *type = [NSString stringWithFormat:@"Content-Type: %@
    ", mimeType];
        [body appendData:YYEncode(type)];
        
        [body appendData:YYEncode(@"
    ")];
        [body appendData:data];
        [body appendData:YYEncode(@"
    ")];
        
        /***************普通参数***************/
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            // 参数开始的标志
            [body appendData:YYEncode(@"--YY
    ")];
            NSString *disposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name="%@"
    ", key];
            [body appendData:YYEncode(disposition)];
            
            [body appendData:YYEncode(@"
    ")];
            [body appendData:YYEncode(obj)];
            [body appendData:YYEncode(@"
    ")];
        }];
        /***************参数结束***************/
        // YY--
    
        [body appendData:YYEncode(@"--YY--
    ")];
        request.HTTPBody = body;
        
        // 设置请求头
        // 请求体的长度
        [request setValue:[NSString stringWithFormat:@"%zd", body.length] forHTTPHeaderField:@"Content-Length"];
        // 声明这个POST请求是个文件上传
        [request setValue:@"multipart/form-data; boundary=YY" forHTTPHeaderField:@"Content-Type"];
        NSUserDefaults *defaults = [NSUserDefaults  standardUserDefaults];
        [request setValue:[defaults objectForKey:@"x-auth-token"] forHTTPHeaderField:@"x-auth-token"];
        
        // 发送请求
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            if (data) {
                NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                NSLog(@"%@", dict);
                [[MyAlertCenter defaultCenter] postAlertWithMessage:@"上传成功"];
                [self.navigationController popViewControllerAnimated:YES];
            } else {
                NSLog(@"上传失败");
                [self.navigationController popViewControllerAnimated:YES];
    
            }
        }];
    }
    
    //本地文件路径
    -(NSMutableDictionary *)localFile{
        //document目录
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        DCFLog(@"%@",paths);
        NSString *path = [paths objectAtIndex:0];
        NSFileManager *fm = [NSFileManager defaultManager];
        NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:path];
        NSString *fileName;
        NSMutableDictionary *R = [NSMutableDictionary dictionary];
        while (fileName = [dirEnum nextObject]) {
            NSLog(@"短路径:%@", fileName);
            NSLog(@"全路径:%@", [path stringByAppendingPathComponent:fileName]);
            NSString *key = [fileName componentsSeparatedByString:@"/"].lastObject;
            [R setObject:[path stringByAppendingPathComponent:fileName] forKey:key];
        }
        //  key为文件名    value为路径
        return R;
    }
    
    
    @end

  • 相关阅读:
    socket.io+angular.js+express.js做个聊天应用(二)
    [原创]Python通过Thrift连接HBase
    [原创]安装Sqoop并验证
    使用PostgreSQL、Hibernate 构建 NoSQL
    [原创]HBase客户端开发举例(第三部分)
    [原创]HBase客户端开发举例(第二部…
    [原创]全分布模式下Hadoop安装
    Samba的基本配置
    常见设计模式举例 转载有改动
    【转载】hibernate中使用ehcache
  • 原文地址:https://www.cnblogs.com/OIMM/p/9858233.html
Copyright © 2011-2022 走看看