程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> ios-圖片沒有上傳到web服務器中

ios-圖片沒有上傳到web服務器中

編輯:編程綜合問答
圖片沒有上傳到web服務器中

上傳一個圖片到web服務器上,但是上傳後之後圖片的名字被保存了,圖片沒保存

代碼:

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissModalViewControllerAnimated:YES];    
    NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);    
    NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
    [urlString appendFormat:@"%@", image];
    NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding
                               allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    NSString *baseurl = @"http://192.168.2.34/Service1.svc/upload/filename.png";    
    NSURL *url = [NSURL URLWithString:baseurl];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [urlRequest setValue:@"application/x-www-form-urlencoded"
      forHTTPHeaderField:@"Content-Type"];
    [urlRequest setHTTPBody:postData];
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
    [connection start];
    NSLog(@"Started!");
}

上傳之後圖片:

CSDN移動問答

但是打開圖片時會顯示空:

CSDN移動問答

最佳回答:


這塊的代碼不對:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
NSMutableString *urlString = [[NSMutableString alloc] initWithFormat:@"name=thefile&&filename=recording"];
[urlString appendFormat:@"%@", image];
NSData *postData = [urlString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
...
[urlRequest setValue:@"application/x-www-form-urlencoded"
  forHTTPHeaderField:@"Content-Type"];
[urlRequest setHTTPBody:postData];

應該換成:

NSData *image = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage], 0.1);
...
[urlRequest setHTTPBody:image];

然後要將 0.1 改為 0.8 或者其他的。不然質量會失真。
需要保證服務器正確讀取數據,根據你的服務器端,在PHP中:

$data = file_get_contents('php://input');
file_put_contents($data, 'filename.jpg');
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved