iphone:使用 ASIFormDataRequest 将图像上传到服务器

发布于 2024-11-05 09:03:29 字数 4221 浏览 1 评论 0原文

我必须将图像上传到我使用 NSMutableURLRequest 为其编写代码的服务器,

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=\"ipodfile%@.jpg\"\r\n",self.fileID] 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]];

我想我的 PHP 脚本响应与此相对应并且工作正常,

我如何在 ASIFormDataRequest 中复制上面的内容?

尝试这样做

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

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

但没有成功?

PHP 脚本的详细信息

<?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}";
}

?>

这是我按照 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]"];

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

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

[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]"];

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

独享拥抱 2024-11-12 09:03:29

使用 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]); 
}

注意 我是凭记忆输入的,因此您可能有一些拼写错误。

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.

心如荒岛 2024-11-12 09:03:29
NSString *strURL = @"enter uerl hear...";

//      ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]]; // Upload a file on disk 
NSString *filename1=[NSString stringWithFormat:@"friendship.jpg"]; 
UIImage *image1=[UIImage imageNamed:filename1];
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0); 
[request setData:imageData1 withFileName:filename1 andContentType:@"image/jpeg" forKey:@"avatar"]; 
[request setRequestMethod:@"POST"];
//[request appendPostData:body]; 
[request setDelegate:self]; 
[request setTimeOutSeconds:3.0]; 
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:@selector(uploadRequestFinished:)]; 
[request setDidFailSelector:@selector(uploadRequestFailed:)]; 
[request startAsynchronous];


- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
 NSLog(@" Error - Statistics file upload failed: \"%@\"",[request responseString]); 
}

- (void)uploadRequestFailed:(ASIHTTPRequest *)request{ 
NSLog(@" Error - Statistics file upload failed: \"%@\"",[[request error] localizedDescription]); 

}
NSString *strURL = @"enter uerl hear...";

//      ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:strURL]]; // Upload a file on disk 
NSString *filename1=[NSString stringWithFormat:@"friendship.jpg"]; 
UIImage *image1=[UIImage imageNamed:filename1];
NSData *imageData1=UIImageJPEGRepresentation(image1, 1.0); 
[request setData:imageData1 withFileName:filename1 andContentType:@"image/jpeg" forKey:@"avatar"]; 
[request setRequestMethod:@"POST"];
//[request appendPostData:body]; 
[request setDelegate:self]; 
[request setTimeOutSeconds:3.0]; 
request.shouldAttemptPersistentConnection = NO;
[request setDidFinishSelector:@selector(uploadRequestFinished:)]; 
[request setDidFailSelector:@selector(uploadRequestFailed:)]; 
[request startAsynchronous];


- (void)uploadRequestFinished:(ASIHTTPRequest *)request
{
 NSLog(@" Error - Statistics file upload failed: \"%@\"",[request responseString]); 
}

- (void)uploadRequestFailed:(ASIHTTPRequest *)request{ 
NSLog(@" Error - Statistics file upload failed: \"%@\"",[[request error] localizedDescription]); 

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文