如何将图像上传到mysql数据库iOS应用程序 [英] How to upload image to mysql database iOS application

查看:57
本文介绍了如何将图像上传到mysql数据库iOS应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iOS 开发的新手,目前正在为我在大学的主要项目创建一个应用程序.我正在创建一个注册页面,要求用户填写他们的详细信息并上传图片.到目前为止,我已经将值发送到数据库,但我不知道如何添加图像选择器选择的图像.有人可以帮忙吗?代码贴在下面....

I'm new to iOS development and currently creating a app for my major project in uni. I'm creating a registration page where the user is asked to fill in their details and also upload an image. So far I've got the values going to the database but I can't figure out how to also add the image that has been selected by the image picker. Could anyone help with this? The code is posted below....

注册视图控制器.h

#import <UIKit/UIKit.h>

#define kpostURL @"http://myurl.com/myphp.php"
#define kfname @"fname"
#define ksname @"sname"
#define kemail @"email"
#define kusername @"username"
#define kpassword @"password"
#define kinstrument @"instrument"
#define klocation @"location"

@interface registrationViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate> {

    UIScrollView *scrollView_;
    BOOL keyboardVisible_;

    IBOutlet UITextField *fnameText;
    IBOutlet UITextField *snameText;
    IBOutlet UITextField *emailText;
    IBOutlet UITextField *usernameText;
    IBOutlet UITextField *passwordText;
    IBOutlet UITextField *instrumentText;
    IBOutlet UITextField *locationText;
    IBOutlet UIImageView *ImageView;
    IBOutlet UIButton *button;

    NSURLConnection *postConnection;
}


@property (nonatomic, retain) UIImagePickerController *imagePicker;
@property (nonatomic, strong) IBOutlet UIScrollView *scrollView;

- (IBAction) pickImage:(id)sender;
- (IBAction) textFieldDoneEditing: (id) sender;
-(IBAction)post:(id)sender;


-(void) postMessage:(NSString*) location withName:(NSString *) fname withSurname:(NSString *) sname withEmail:(NSString *) email withUsername:(NSString *) username withPassword:(NSString *) password withInstrument:(NSString *) instrument;

- (void) keyboardDidShow:(NSNotification *)notif;
- (void) keyboardDidHide:(NSNotification *)notif;

@end

RegistrationViewController.m

RegistrationViewController.m

#import "registrationViewController.h"
#import <QuartzCore/QuartzCore.h>

@implementation registrationViewController

@synthesize imagePicker;
@synthesize scrollView=scrollView_;

- (IBAction)textFieldDoneEditing:(id)sender {
    [sender resignFirstResponder];
}


- (IBAction)pickImage:(id)sender {
    imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:imagePicker animated:YES];
}

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
        ImageView.image = image;
    [imagePicker dismissModalViewControllerAnimated:YES];
}


- (void) imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [imagePicker dismissModalViewControllerAnimated:YES];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];

}


-(void) postMessage:(NSString*) location withName:(NSString *) fname withSurname:(NSString *) sname withEmail:(NSString *) email withUsername:(NSString *) username withPassword:(NSString *) password withInstrument:(NSString *) instrument{


    if (fname != nil && location != nil && sname !=nil && email !=nil && username !=nil && password !=nil && instrument !=nil){

        NSMutableString *postString = [NSMutableString stringWithString:kpostURL];

        [postString appendString:[NSString stringWithFormat:@"?%@=%@", kfname, fname]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", ksname, sname]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kemail, email]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kusername, username]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kpassword, password]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", kinstrument, instrument]];

        [postString appendString:[NSString stringWithFormat:@"&%@=%@", klocation, location]];

        [postString setString:[postString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:postString]];
        [request setHTTPMethod:@"POST"];

        postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];


    }

}

-(IBAction)post:(id)sender{

    [self postMessage:locationText.text withName:fnameText.text withSurname:snameText.text withEmail:emailText.text withUsername:usernameText.text withPassword:passwordText.text withInstrument:instrumentText.text];
    [locationText resignFirstResponder];
    fnameText.text = nil;
    snameText.text = nil;
    emailText.text = nil;
    usernameText.text = nil;
    passwordText.text = nil;
    instrumentText.text = nil;
    locationText.text = nil;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Test1" object:self];

}

- (void)viewDidUnload
{
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{

    NSLog(@"%@", @"Registering for keyboard events...");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
    keyboardVisible_ = NO;

    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{

    NSLog(@"%@", @"Unregistering for keyboard events...");
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

#pragma mark -
#pragma mark Keyboard handlers

- (void) keyboardDidShow:(NSNotification *)notif {
    NSLog(@"%@", @"Received UIKeyboardDidShowNotification");

    if (keyboardVisible_) {
        NSLog(@"%@", @"Keyboard is already visible.  Ignoring notifications.");
        return;
    }

    // The keyboard wasn't visible before
    NSLog(@"Resizing smaller for keyboard");

    // Get the origin of the keyboard when it finishes animating
    NSDictionary *info = [notif userInfo];
    NSValue *aValue = [info objectForKey:UIKeyboardFrameEndUserInfoKey];

    // Get the top of the keyboard in view's coordinate system. 
    // We need to set the bottom of the scrollview to line up with it
    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];
    CGFloat keyboardTop = keyboardRect.origin.y;

    // Resize the scroll view to make room for the keyboard
    CGRect viewFrame = self.view.bounds;
    viewFrame.size.height = keyboardTop - self.view.bounds.origin.y;

    self.scrollView.frame = viewFrame;
    keyboardVisible_ = YES;
}

- (void) keyboardDidHide:(NSNotification *)notif {
    NSLog(@"%@", @"Received UIKeyboardDidHideNotification");

    if (!keyboardVisible_) {
        NSLog(@"%@", @"Keyboard already hidden.  Ignoring notification.");
        return;
    }

    // The keyboard was visible
    NSLog(@"%@", @"Resizing bigger with no keyboard");

    // Resize the scroll view back to the full size of our view
    self.scrollView.frame = self.view.bounds;
    keyboardVisible_ = NO;
}

@end

提前致谢:)

推荐答案

这是我在 NSMutableURLRequest 上创建的一个类别:

Here is a category that I've created on NSMutableURLRequest:

@interface NSMutableURLRequest (SendFormData)

-(void)sendFormData:(NSDictionary *)data;

@end

@implementation NSMutableURLRequest (SendFormData)

-(void)sendFormData:(NSDictionary *)data{
    // add boundary
    NSMutableString *boundary = [NSMutableString stringWithString:@"----Boundary+"];

    // append 5 random chars to the end of the boundary
    for(int i = 0; i < 5; i++){
        BOOL lowercase = arc4random() % 2;
        if(lowercase){
            [boundary appendFormat:@"%c", (arc4random() % 26) + 97];
        } else{
            [boundary appendFormat:@"%c", (arc4random() % 26) + 65];
        }
    }

    // create body data
    NSMutableData *body = [[NSMutableData alloc] init];

    self.HTTPMethod = @"POST";
    [self setValue:[NSString stringWithFormat:@"multipart/form-data, boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];

    for(NSString *currentKey in [data allKeys]){
        id currentObject = [data objectForKey:currentKey];
        if([currentObject class] == [UIImage class]){
            [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary]  dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"myphoto.png\"\r\n", currentKey] dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:[@"Content-Type: image/x-png\r\n" dataUsingEncoding:NSASCIIStringEncoding]];
            [body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
            [body appendData:UIImagePNGRepresentation(currentObject)];
            [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        } else{
            [body appendData:[[NSString stringWithFormat:@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n", boundary, currentKey, currentObject] dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO]];
        }
    }

    self.HTTPBody = body;
}

@end

只需将参数和参数对象的 NSDictionary 传递给它,它就会创建您的请求,然后您可以将其传递给 NSURLConnection.

或者您可以选择查看 ASIFormDataRequest 以获取此类内容 (https://github.com/pokeb/asi-http-request/tree).

Just pass it a NSDictionary of your parameters and the parameters' objects, and it will create your request that you can then pass to a NSURLConnection.

Or you optionally can look into ASIFormDataRequest for such things (https://github.com/pokeb/asi-http-request/tree).

这篇关于如何将图像上传到mysql数据库iOS应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆