Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
71 views
in Technique[技术] by (71.8m points)

asihttprequest - iphone: upload image to server using ASIFormDataRequest

I have to upload an image to server for which I wrote code using NSMutableURLRequest like this

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:@"
--%@
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile%@.jpg"
",self.fileID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream

"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"
--%@--
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

I guess my PHP script respond corresponding to this and is working fine

how can I replicate above in ASIFormDataRequest?

tried to do this

ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL: 
                               [NSURL URLWithString:photoUploadURLString]]; 


NSString *boundary = [NSString stringWithString:@"---------------------------14737809831466499882746641449"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];

    NSMutableData *body = [NSMutableData data];
    [body appendData:[[NSString stringWithFormat:@"
--%@
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];    
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name="userfile"; filename="ipodfile%@.jpg"
",self.fileID] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream

"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[NSData dataWithData:imageData]];
    [body appendData:[[NSString stringWithFormat:@"
--%@--
",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request addData:body withFileName:filename andContentType:@"image/jpeg" forKey:@"snapshot[image]"]; 
request.uploadProgressDelegate = self.progressView; 
[request setDidFinishSelector:@selector(getFacebookPhotoFinished:)];

but didnt got sucess?

here are the details of my PHP scripts

<?php 

$uploaddir = './uploads/';
$file = basename($_FILES['userfile']['name']);
$uploadfile = $uploaddir . $file;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
        echo "http://example.com/uploads/{$file}";
}

?>

I did as per Cyprian

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"images/ipodfile%@.jpg", fileID]];
NSData *imageData = UIImageJPEGRepresentation([itemImageView image], 0.05);
if (imageData != nil) {
    [imageData writeToFile:savedImagePath atomically:YES];
}
if ([[NSFileManager defaultManager] createFileAtPath:savedImagePath contents:imageData attributes:nil])
{
    NSLog(@"Image saved");
} else {
    NSLog(@"Image not saved");
}           


[activityIndicator startAnimating];
NSString *photoUploadURLString = @"http://example.com/imageuploader.php";

NSString* filename = [NSString stringWithFormat:@"ipodfile%@.jpg", self.fileID];
NSLog(@"url  is %@/%@",photoUploadURLString, filename);

UIImage *newImage = [[UIImage alloc] init];
newImage=[itemImageView image];
NSURL *url=[NSURL URLWithString:photoUploadURLString];

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"userfile" forKey:@"name"];
[request setPostValue:filename forKey:@"filename"];

[request setData:imageData withFileName:filename andContentType:@"image/jpeg" forKey:@"snapshot[image]"];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Uploading file to server using ASIFormDataRequest

-(void)uploadFile{
        NSURL *url = [NSURL URLWithString: photoUploadURLString];

        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

        [request setUseKeychainPersistence:YES];
        //if you have your site secured by .htaccess

        //[request setUsername:@"login"];
        //[request setPassword:@"password"];


        NSString *fileName = [NSString stringWithFormat:@"ipodfile%@.jpg",self.fileID];
        [request addPostValue:fileName forKey:@"name"];

        // Upload an image
        NSData *imageData = UIImageJPEGRepresentation([UIImage imageName:fileName])
        [request setData:imageData withFileName:fileName andContentType:@"image/jpeg" forKey:@"userfile"];

        [request setDelegate:self];
        [request setDidFinishSelector:@selector(uploadRequestFinished:)];
        [request setDidFailSelector:@selector(uploadRequestFailed:)];

        [request startAsynchronous];
}

- (void)uploadRequestFinished:(ASIHTTPRequest *)request{    
    NSString *responseString = [request responseString];
        NSLog("Upload response %@", responseString);
}

- (void)uploadRequestFailed:(ASIHTTPRequest *)request{

        NSLog(@" Error - Statistics file upload failed: "%@"",[[request error] localizedDescription]); 
}

Note I was typing from memory so you may have some misspellings.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...