不在服务器上传图像

时间:2017-08-29 06:37:22

标签: ios objective-c

我正在使用此代码

NSString *strrrr=@"";
UIImage *chooseImage=[infoDict valueForKey:@"filename"];

if (chooseImage)
{
    strrrr=@"filename.JPG";
}                                                                       

urlString=[NSString stringWithFormat:@"%@KabuterCompanyService?companyID=%@&companyTypeID=%@&serviceTypeID=%@&description=%@&serviceCreatedBy=%@&startDate=%@&endDate=%@&location=%@&promotionalText=%@&promotionalDocument=%@&colOfResponseOptionVO=%@&responseOptionQuestionVO=%@&componentName=%@&companyServiceID=%@&submit=%@&quickSend=%@&ajaxreq=%@&access_token=%@&commandResultAttributes : promotionalDocumentVO.mimeTypeVO.name,companyVO.companyName,serviceTypeVO.name,colOfOwnerEntitlementVO.entitlementID,colOfOwnerEntitlementVO.entitleableID,colOfSubscriberEntitlementVO.entitlementID,colOfSubscriberEntitlementVO.entitleableID,colOfResponseOptionVO.sequenceNumber,colOfResponseOptionVO.attributeValue,colOfResponseOptionVO.url,colOfResponseOptionVO.expiresOn,responseOptionQuestionVO.attributeValue,*",BaseURL2,[infoDict valueForKey:@"vendorID"],@"893688751",@"-2114174907",[infoDict valueForKey:@"EventName"],[infoDict valueForKey:@"HostName"],[infoDict valueForKey:@"StartDate"],[infoDict valueForKey:@"EndDate"],[infoDict valueForKey:@"Location"],[infoDict valueForKey:@"EventDescription"],strrrr,[infoDict valueForKey:@"colOfRequestParameterVO"],[infoDict valueForKey:@"responseOptionQuestionVO"],@"KabuterCompanyService",@"null",@"Create",@"true",@"json",[[NSUserDefaults standardUserDefaults] objectForKey:@"tokenID"]];

urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];

NSData *imageData = UIImageJPEGRepresentation(chooseImage, 1.0);

[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:60];
[request setHTTPMethod:@"POST"];

NSString *boundary = @"WebKitFormBoundaryjrFKfnmMBcXRMamI";

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@\r\n\r\n", @"imageCaption"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", @"Some Caption"] dataUsingEncoding:NSUTF8StringEncoding]];

// add image data
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; name=filename.JPG\r\n", @"name"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];


[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
    if(data.length > 0)
    {
        //success
    }
}];

不在服务器上传我的图片当我的Android团队做同样的事情他们在服务器上使用这个Android PLZ帮助我

如果有人知道为什么我无法在服务器上获取我的图片,请提供帮助。

2 个答案:

答案 0 :(得分:0)

您的请求应该是:

NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];

// how to send   parameters with request that you ma need when also uload  image //


       [_params setObject:promotionalDocument    forKey:[NSString stringWithFormat:@"promotionalDocument"]];
       [_params setObject:mobile   forKey:[NSString stringWithFormat:@"mobile"]];






        // the boundary random string, that will not repeat in post data

        NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";

        // your server paramter for image
        NSString* FileParamConstant = @"serverParamterForImage";

        // the server url to which the image (or the media) is uploaded. Use your server url here
        NSURL* requestURL = [NSURL URLWithString:@"your URL"];

        // create request
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
        [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
        [request setHTTPShouldHandleCookies:NO];
        [request setTimeoutInterval:30];
        [request setHTTPMethod:@"POST"];

        // set Content-Type in HTTP header
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
        [request setValue:contentType forHTTPHeaderField: @"Content-Type"];

        // post body
        NSMutableData *body = [NSMutableData data];

        // add params (all params are strings)
        for (NSString *param in _params) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
        }




        // add image data
        NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
        if (image) {
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:imageData];
            [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        }



        [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

        // setting the body of the post to the reqeust
        [request setHTTPBody:body];

        // set the content-length
        NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        // set URL
        [request setURL:requestURL];

// then you can use that request

答案 1 :(得分:0)

我面临同样的问题。但我没有使用 NSMutableURLRequest 获得解决方案。您可以使用 AFNetworking NSURLSessionUploadTask

<强> NSURLSessionUploadTask:

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

NSURL *url = YOUR_SERVICE_URL;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];

[request setHTTPMethod:@"PUT"];

UIImage *image = [UIImage imageNamed:@"imageName"];
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

NSURLSessionUploadTask *taskUpload = [session uploadTaskWithRequest:request fromData:imageData completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse*) response;
    if (!error && httpResp.statusCode == 200) {

        // Uploaded

    } else {

       NSLog(@"ERROR: %@ AND HTTPREST ERROR : %ld", error, (long)httpResp.statusCode);
      }
}];

<强> AFNetworking:

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    [manager POST:YOUR_SERVICE_URL parameters:YOUR_PARAMETER_DICTIONARY constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
     {
             [formData appendPartWithFormData:IMAGE_DATA name:YOUR_KEY_NAME];

     } progress:^(NSProgress * _Nonnull uploadProgress)
     {
     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
     {
         NSLog(@"%@",responseObject);

     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
     }];