使用xcode从数据库将图像上载到Web服务

时间:2015-04-28 06:39:24

标签: ios objective-c iphone xcode

朋友们,我是ios的新人, 我需要将图像从手机上传到网络服务我的链接如下 " http://dev9.edisbest.com/upload_image.php" 我的代码如下:

@echo off
    setlocal enableextensions disabledelayedexpansion

    call :select "someDir\*" THE_FILE
    echo You picked %THE_FILE%

    goto :eof


:select mask returnVar
    setlocal enableextensions disabledelayedexpansion

    rem Configure internal variables
    set "fileNumber="
    set "maxFiles=-1"
    for /f "delims==" %%a in ('2^>nul set f[') do set "%%a="

    echo Enter the number of the file you want to select:

    rem Search files, show list and create array with file list
    rem Using xcopy to get the list of files because it will show
    rem relative paths when a relative mask is used as input 
    for /f "tokens=1,* delims=:" %%a in ('
        xcopy "%~1" "%temp%" /l ^| findstr /n /r /c:"[\\\.:]"
    ') do (
        echo %%a^) %%b
        set "f[%%a]=%%~fb"
        set "maxFiles=%%a"
    )

    rem Prompt 
    :select.ask
    set /p "fileNumber=#? "

    rem Validate input
    set /a "fileNumber=fileNumber+0" 2>nul
    if %fileNumber% gtr %maxFiles% set "fileNumber=-1"
    if %fileNumber% lss 1 set "fileNumber="
    if not defined fileNumber (
        echo Wrong selection
        goto :select.ask
    )

    rem Retrieve file from array
    setlocal enabledelayedexpansion
    for %%a in ("!f[%fileNumber%]!") do (
        endlocal 
        set "selectedFile=%%~a"
    )

    rem Return selection to caller
    endlocal & set "%~2=%selectedFile%"
    goto :eof

当我构建并运行时,我将被要求选择图像,并选择要上传的图像

我收到一条消息,

-(IBAction) post:(id) sender
{
    count = 0;
    self.progress = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];

    self.progress.center = self.view.center; 
    progress.hidden = NO;
    [self.view addSubview:self.progress];
    nmyTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateUI:) userInfo:nil repeats:YES];
    NSString *filename = [NSString alloc];
    filename = [self randomStringWithLength:5];
    NSData *imageData = UIImageJPEGRepresentation(imageView.image, 100);
    NSError *error;
    NSData *searchData;
    NSHTTPURLResponse *response;

    // setting up the URL to post to
    NSString *urlString = @"http://dev9.edisbest.com/upload_image.php";

    // setting up the request object now

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];

    /*
     add some header info now
     we always need a boundary when we post a file
     also we need to set the content type

     You might want to generate a random boundary.. this is just the same 
     as my output from wireshark on a valid html post
     */
    NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    /*
     now lets create the body of the post
     */

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

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@.jpg\"\r\n",filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    // setting the body of the post to the reqeust
    searchData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    NSLog(@"%@",response);
    NSString *imageName;
    imageName = [[NSString alloc] initWithData:searchData encoding:NSUTF8StringEncoding];

    NSLog(@"retrun Result of Upload Photo.. %@",imageName);

    [request setHTTPBody:body];

    // now lets make the connection to the web

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]                            completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 
    {                                NSLog(@"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);  }];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    ///self.returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",returnString);

   }

请指导我

2 个答案:

答案 0 :(得分:1)

以下是我的项目上传图片的代码 //创建请求

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(imageToPost, 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] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithString:@"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:@"%d", [body length]];
 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

  // set URL
  [request setURL:requestURL];

答案 1 :(得分:1)

试试这个..

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


NSString *encodedString = [imageData base64EncodedStringWithOptions:0];

NSMutableDictionary *dictionnary = [NSMutableDictionary dictionary];
[dictionnary setObject:encodedString forKey:@"imageData"];


NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionnary
                                                   options:kNilOptions
                                                     error:&error];

NSString *urlString = @"http://Your url";
NSURL *url = [NSURL URLWithString:urlString];

// Prepare the request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
[request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[jsonData length]]  forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:jsonData];

NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&theResponse
                                                 error:&errorReturned];