美文网首页
图片上传

图片上传

作者: Yanni_L | 来源:发表于2016-11-03 10:07 被阅读36次

    项目中用到图片上传, 本来准备使用AFN 的 但是发现用AFN 后台接收不到图片流.
    就自己用系统自带的网络库写了个上传图片的请求

    // 1.创建Session
        NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:actoion delegateQueue:[NSOperationQueue mainQueue]];
        
        NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://172.16.151.152:8080/picServer/pic/upload"]];
        [request addValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
        [request addValue:@"text/html" forHTTPHeaderField:@"Accept"];
        [request addValue:@"Application/Json" forHTTPHeaderField:@"Accept"];
        [request setHTTPMethod:@"POST"];
        [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
        [request setTimeoutInterval:20];
        NSData * imageData = UIImageJPEGRepresentation(img,0.8);
        NSString *picStr = [NSString stringWithFormat:@"%@%@|",LYUserDefaultForKey(userAccountKey),name];
        
        NSData *picName = [picStr dataUsingEncoding:NSUTF8StringEncoding];
        
        NSMutableData *mData = [NSMutableData dataWithData:picName];
        [mData appendData:imageData];
        
        
        NSURLSessionUploadTask * uploadTask = [session uploadTaskWithRequest:request fromData:mData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
            
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    
            loadResult(dict);
    
        }];
        
    //    uploadTask.
        [uploadTask resume];
    
    

    如果需要监控上传的进度那就需要设置代理对象, 遵守NSURLSessionTaskDelegate协议

    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
    {
        //    NSLog(@"didSendBodyData");
        NSLog(@"+++++%f", 1.0 * totalBytesSent / totalBytesExpectedToSend);
    
    }
    

    注: 如果上传有问题, 那么可能请求头设置有问题, 那么就可以用青花瓷, 抓上送报文, 就可以看到, 那个请求头设置错误就会有提示.

    相关文章

      网友评论

          本文标题:图片上传

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