将图像上传到服务器

时间:2018-02-26 06:36:39

标签: ios objective-c json image-uploading

我的代码来自此链接

Uploading Image via POST in Objective C

// COnvert Image to NSData
NSData *dataImage = UIImageJPEGRepresentation(_chosenImage, 1.0f);
NSLog(@"%@", dataImage);
NSString *tempURLString = [APIStr stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];

// set your URL Where to Upload Image
NSString *urlString = @"My URL String";

// set your Image Name
NSString *filename = @"My File Name";

// Create 'POST' MutableRequest with Data and Other Image Attachment.
NSMutableURLRequest* request= [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
NSLog(@"%@", request);
[request setHTTPMethod:@"POST"];    
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@_.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"%@", postbody);
[postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:dataImage]];
[postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];

// Get Response of Your Request
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"Response  %@",responseString);

此代码对我不起作用..我收到失败的消息。我的代码有问题。

我也试过这段代码

https://jmsliu.com/3241/select-and-upload-multiple-photos-from-gallery-or-camera-in-ios.html

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

_chosenImage = info[UIImagePickerControllerEditedImage];
   [self uploadImageLegacy:_chosenImage];
}


- (void) uploadImageLegacy:(UIImage *)image {
NSString *tempURLString = [Str stringByReplacingOccurrencesOfString:@"***" withString:@"upload"];
//upload single image
NSURL *url = @"My URL here";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];
[request setHTTPMethod:@"POST"];
NSString *POST_BODY_BOURDARY = @"SportuondoFormBoundary";
NSString *contentTypeValue = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", POST_BODY_BOURDARY];
[request addValue:contentTypeValue forHTTPHeaderField:@"Content-type"];

NSMutableData *dataForm = [NSMutableData alloc];
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"param1\";\r\n\r\n%@", @"10001"] dataUsingEncoding:NSUTF8StringEncoding]];

NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"my_upload_file_name\"; filename=\"%@.jpg\"\r\n", @"test"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[[NSString stringWithFormat:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[dataForm appendData:[NSData dataWithData:imageData]];

[dataForm appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",POST_BODY_BOURDARY] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:dataForm];
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend {
NSLog(@"Sent %lld, Total sent %lld, Not Sent %lld", bytesSent, totalBytesSent, totalBytesExpectedToSend);
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
_receiveData = [NSMutableData data];
[_receiveData setLength:0];
completionHandler(NSURLSessionResponseAllow);
NSLog(@"NSURLSession Starts to Receive Data");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data {
[_receiveData appendData:data];
NSLog(@"NSURLSession Receive Data");
}

 - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSLog(@"URL Session Complete: %@", task.response.description);

if(error != nil) {
    NSLog(@"Error %@",[error userInfo]);
} else {
    NSLog(@"Uploading is Succesfull");

    NSString *result = [[NSString alloc] initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", result);
}
}

1 个答案:

答案 0 :(得分:1)

我正在使用此代码并为我工作

    NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
    [_params setObject:[UserDict valueForKey:@"userid"] forKey:@"userid"];
    // YOU CAN ADD YOUR  PARAMETERS HERE


    NSString *BoundaryConstant = @"----------V2ymHFg03ehbqgZCaKO6jy";
    NSString* FileParamConstant = @"file";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];

    NSMutableData *body = [NSMutableData data];

    //    NSData *bodyData = [appData createFormData:_params withBoundary:BoundaryConstant];
    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]];
    }
    // I AM RESIZING IMAGE YOU CAN SKIP
    UIImage *newSizeImage = [self imageWithImage:currentlyCapturedImage scaledToSize:newImageSize];

    NSData *imageData = UIImageJPEGRepresentation(newSizeImage, 1.0);

    if (imageData) {
        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image%@.jpg\"\r\n",FileParamConstant, timestamp] 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]];

现在您拥有body参数和图片。

您可以将其用作请求主体[request setHTTPBody:body];

并致电服务

希望它会有所帮助

修改

NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

}];

[postDataTask resume];