美文网首页
上传文件的API(参考)

上传文件的API(参考)

作者: 爱掏蜂窝的熊 | 来源:发表于2015-12-10 17:49 被阅读932次

    这个API是用来上传文件的,具体项目具体分析.
    项目例子:

    // 如果未上传则调用接口上传
        NSData * fileData = [[NSData alloc] initWithContentsOfFile:path];
        if (!fileData) {
            return nil;
        }
        // 上传成功,返回服务器的URLStr
        NSInteger errorCode = 0;
        NSString * fileURI = [CMDataRequestProtocol uploadFileData:fileData
                                                      withFileName:@"uploadPic"
                                                       withFileExt:@"jpg"
                                                     withErrorCode:&errorCode];
    
        if (errorCode) {
            return nil;
        }else{
            if (!fileURI) {
                fileURI = @"";
            }
            return fileURI;
        }
    

    上传文件的方法

    /**
     *  @method + (NSString *)uploadFileData:(NSData *)fileData withErrorCode:(NSInteger *)errorCode
     *
     *  @abstract 上传文件
     *
     *  @param fileData   文件数据
     *  @param errorCode  [out]错误代码
     *
     *  @return 如果上传成功则返回资源路径
     */
    + (NSString *)uploadFileData:(NSData *)fileData
                    withFileName:(NSString *)fileName
                     withFileExt:(NSString *)fileExt
                   withErrorCode:(NSInteger *)errorCode
    {
        NSMutableString * uploadFileURL = [[NSMutableString alloc] initWithCapacity:20];
        [uploadFileURL appendFormat:@"http://%@/upload_file",UPLOAD_HOST];
        [uploadFileURL appendFormat:@"?%@",[self getURLSuffixWithURL]];
        
        //创建Request对象
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setURL:[NSURL URLWithString:uploadFileURL]];
        [request setHTTPMethod:@"POST"];
        NSMutableData *body = [NSMutableData data];
        
        //设置表单项分隔符
        NSString *boundary = @"---------------------------20140601chrrsmusic1703";
        
        //设置内容类型
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        
        //写入图片的内容
        NSString * fileFullName = [NSString stringWithFormat:@"%@.%@",fileName,fileExt];
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n",fileName,fileFullName] dataUsingEncoding:NSUTF8StringEncoding]];
        NSString * contentTypeStr = [NSString stringWithFormat:@"Content-Type: image/%@\r\n\r\n",fileExt];
        [body appendData:[contentTypeStr dataUsingEncoding:NSUTF8StringEncoding]];
        //    NSString * appendDataStr = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding];
        //    DELOG(@"appendDataStr: \r\n%@",appendDataStr);
        [body appendData:fileData];
        [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        //写入尾部内容
        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [request setHTTPBody:body];
        
        NSHTTPURLResponse *urlResponese = nil;
        NSError *error = [[NSError alloc]init];
        NSData* resultData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponese error:&error];
        if (!resultData) {
            *errorCode = -1;
            return nil;
        }
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingMutableLeaves error:nil];
        NSInteger statusCode = [[NSString ensureStringFor:[jsonData objectForKey:@"state"]] integerValue];
        *errorCode = statusCode;
        if (statusCode == 402) {
            // 发出需要登录的通知
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_NEED_LOGINTOKEN
                                                                    object:nil];
            });
        }
        
        if (statusCode != 0) {
            *errorCode = statusCode;
            return nil;
        }else{
            NSDictionary * data = [jsonData objectForKey:@"data"];
            if (![data isKindOfClass:[NSDictionary class]]) {
                return nil;
            }else{
                NSString * fileURL = [NSString ensureStringFor:[data objectForKey:@"uri"]];
                return fileURL;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题: 上传文件的API(参考)

          本文链接:https://www.haomeiwen.com/subject/vedehttx.html